//给定一个十进制整数N,求出从1到N的所有整数中出现”1”的个数。
int cal_num_of_1(int n)
{
int count = 0;
int temp;
for (int i = 1; i<n+1; i++)
{
temp = i;
while (temp>0)
{
if (temp%10 == 1)
{
count++;
}
temp = temp/10;
}
}
return count;
}
int cal_num_of_1_2(int n)
{
//1的个数
int count = 0;
//当前位
int factor = 1;
//低位数字
int lower_num = 0;
//当前位数字
int cur_num = 0;
//高位数字
int higher_num = 0;
if (n<=0)
{
return 0;
}
while (0 != n/factor)
{
//低位数字
lower_num = n-(n/factor)*factor;
//当前位数字
cur_num = (n/factor)%10;
//高位数字
higher_num = n/(factor*10);
switch (cur_num)
{
case 0:
count += higher_num*factor; //如果为0,出现1的次数由高位决定:等于高位数字 * 当前位数
break;
case 1:
count += higher_num*factor + lower_num + 1;//如果为1,出现1的次数由高位和低位决定:高位数字 * 当前位数 + 低位数字 + 1
break;
default:
count += higher_num*factor + factor; //如果大于1,出现1的次数由高位决定:(高位数字+1)* 当前位数
break;
}
factor *= 10; //前移一位
}
return count;
}
给定一个十进制整数N,求出从1到N的所有整数中出现”1”的个数
最新推荐文章于 2023-09-22 01:25:57 发布