一些题目

第一题,是求从a与b之间的数相加,简单的实现如下


def sum_a_to_b(a, b)
        result = 0
    if a.is_a?(Integer) && b.is_a?(Integer)
        if a > b
            result = Array(b..a).sum
        else
            result = Array(a..b).sum
        end
    end
    result
end

以上的实现其实还可以优化,利用连加公式:n(n+1)/2 ,可以有效降低复杂度。

def sum_a_to_b(a, b)
        result = 0
    if a.is_a?(Integer) && b.is_a?(Integer)
      if a > b
        result = a * (a + 1) / 2 - (b - 1) * b / 2 
      else
        result = b * (b + 1) / 2 - (a - 1) * a / 2 
    end
    else
        result = '请输入数字'
    end
    result
end

继续优化一行代码

def sum_a_to_b(a, b)
 (a + b) * ((b - a).abs + 1) / 2
end

测试结果


image.png

第二题,一个字符串中是否包含重复的字符


def is_repeat?(str)
    compare_str = str.upcase
    len = compare_str.length

    if len > 24
        return true
    else
        compare_hash = compare_str.each_char.with_index.inject(Hash.new{ |h, k| h[k] = []}) do |init, num|
            init[num[0]] << num[1] + 1
            init
        end
        compare_hash.each do |compare|
            if compare[1].length > 1
                return true
            end
        end
    end
    return false
end


is_repeat?("avc")
is_repeat?("avcC")
is_repeat?("avcv")

第三题,一串乱序数字按从大到小排序输出


def sort(nums)
    result = ""
    nums_str = nums.to_s
    num_hash = nums_str.each_char.with_index.inject(Hash.new{ |h, k| h[k] = []}) do |init, num|
        init[num[0].to_i] << num[1] + 1
        init
    end

    num_hash.each do |key, value|
        value.length.times do 
            result << key.to_s
        end
    end
    result.reverse.to_i

end

sort(12323)


最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容