您的位置:首页 > 其它

给定一个十进制整数N,求出从1到N的所有整数中出现”1”的个数

2013-08-17 17:56 671 查看
//给定一个十进制整数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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐