编程之美---1的个数C#笨(效率低)方法实现

编程之美—1的个数C#笨(效率低)的方法实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class Program
{
static void Main(string[] args)
{
Program p = new Program();
Console.WriteLine(p.count_1_in_a_bounch_of_nums(13));
Console.Read();
}

public int count_1_in_a_num(int num)
{
int count = 0;
while (num != 0)
{
count += (num % 10) == 1 ? 1 : 0;
num /= 10;
}

return count;
}

public int count_1_in_a_bounch_of_nums(int end)
{
int count = 0;
for (int i = 1; i <= end; i++)
{
count += count_1_in_a_num(i);
}

return count;
}
}