`
bxp2012
  • 浏览: 2301 次
最近访客 更多访客>>
文章分类
社区版块
存档分类
最新评论

统计0到n的所有数字中1出现的次数

阅读更多
思路:先把所有的数字拼接成为一个大字符串,然后统计这个字符串中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
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics