---
title: "统计0到n的所有数字中1出现的次数"
author: "bxp2012"
date: "2013-04-23T09:19:02Z"
tags: []
categories: ["编程语言"]
slug: "0-n-1"
draft: false
lastmod: "2013-04-23T09:19:02Z"
id: 1851764
url: "https://bxp2012.iteye.com/blog/1851764"
---

思路：先把所有的数字拼接成为一个大字符串，然后统计这个字符串中1出现的次数。
具体代码如下：


```java

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

```