思路:先把所有的数字拼接成为一个大字符串,然后统计这个字符串中1出现的次数。
具体代码如下:
具体代码如下:
require 'test/unit'
class TestCountN < Test::Unit::TestCase
def test
assert_equal 6, count(13)
end
end
def add_all_number_to_str n
str = ""
for i in 1..n
str += i.to_s
end
str
end
def count n
c = 0
add_all_number_to_str(n).each_char {|x| c=c+1 if(x.to_i)==1}
c
end