输入两个整数a和b,求a和b之间1出现的次数。
代码如下:
#include<stdio.h>
void swap(int* a, int* b)
{
int tmp = *a;
*a = *b;
*b = tmp;
}
int NumOf1(int n)
{
if (0 == n)
{
return 0;
}
int tmp = n;
int sum = 0;
int rem, base = 1; //rem表示当前数位上的数字,base表示当前数位
while (tmp)
{
rem = tmp % 10;
tmp /= 10;
if (0 == rem)
{
sum += (tmp * base); //rem为0,只需计算高位变化时当前数位1的个数
}
else if (1 == rem)
{
sum += (n - (n / base) * base + 1 + tmp * base); //rem为1,还需计算低位变化时当前数位1的个数
}
else
{
sum += ((tmp + 1) * base); //rem>1,还需计算低位变化时当前数位1的个数
}
base *= 10;
}
return sum;
}
int main()
{
int a, b;
while (scanf("%d %d", &a, &b) != EOF)
{
//调整a和b的顺序
if (a > b)
{
swap(&a, &b);
}
if (0 == a)
{
printf("%d\n", NumOf1(b) );
continue;
}
printf("%d\n", (NumOf1(b) - NumOf1(a - 1)) );
}
return 0;
}