题目:输入一个整数n,求从1到n这n个整数的十进制表示中1出现的次数。
例如输入12,从1到12这些整数中包含1 的数字有1,10,11和12,1一共出现了5次。
要在一个数字中找到1的个数,可以简单地把数字转换成字符串,然后扫描字符串,判断每个字符是否为1,如果为1就把1的个数加1.
另一种解法是通过除法和取模判断1的个数。首先,当数字为1位数时,将其除以10取模,然后判断是否为1,如果为1,就将1的个数相加。如果数字为多为数,则将其不断除以10,如果结果为1,则1的个数加1,直到数字个数为1.
算法伪代码如下:
assign value from 1 to n arr
//count the number of one from 1 to n
for i <- 0 to n
temp = arr[i];
while(temp/10 != 0)
if temp/10 == 1
then add sum
temp /= 10;
if arr[i]%10 == 1
then add sum
C++实现
int CountOne(const int &n)
{
int arr[n];
int sum = 0;
int temp = 0;
//assign value from 1 to n arr
for(int i = 0; i != n; ++i)
{
arr[i] = i+1;
}
//count the number of one from 1 to n
//for i <- 0 to n
for(int i = 0; i != n; ++i)
{
temp = arr[i];
while(temp/10 != 0)
{
//if temp/10 == 1
if(temp / 10 == 1)
{
//then add sum
++sum;
}
temp /= 10;
}
//if arr[i]%10 == 1
if(arr[i] % 10 == 1)
{
//then add sum
++sum;
}
}
return sum;
}
请多多指教!