锁定老帖子 主题:一道关于Ruby的面试题
精华帖 (0) :: 良好帖 (0) :: 隐藏帖 (0)
|
|
---|---|
作者 | 正文 |
发表时间:2012-08-10
抱歉忘记这里是ruby版,用了java实现。
|
|
返回顶楼 | |
发表时间:2012-08-15
# test case def check(i) if i.zero? false elsif 1 == i % 10 true else check(i / 10) end end # the f function def f(range = 0..0) if range.is_a? Range raise "Invalid range values. Must be integer." unless range.begin.is_a?(Integer) and range.begin.is_a?(Integer) raise "Range values must be bigger than -1" unless range.begin >= 0 and range.end >= 0 raise "Range begin must not be bigger than the end" unless range.begin <= range.end range.inject(0) do |sum, i| if check(i) sum.succ else sum end end else raise "Please input range" end end # test puts f(0..ARGV[0].to_i) |
|
返回顶楼 | |
发表时间:2012-08-15
python 代码
import math def length11(n): return int( math.log10(n) ) def first(n): return n/pow(10, length11(n)) def tail(n): return n % pow(10, length11(n)) def f9(k): if k == 0: return 0 return pow(10, k-1) + 10*f9(k-1) def f1(n): if first(n) == 1: return tail(n) + 1 else: return pow(10, length11(n)) def cal(n): if n== 0: return 0 if n <= 9: return 1 return f1(n) + first(n) * f9(length11(n))+ cal(tail(n)) print cal(213) print cal(10) |
|
返回顶楼 | |
发表时间:2012-08-22
实际上就是进制转换算法的变形
def get_one_count(from, to, base=10) sum = 0 for n in (from .. to) do begin r = n % base n = (n / base).floor sum += 1 if r == 1 end while n != 0 end return sum end puts get_one_count(0, 13) |
|
返回顶楼 | |