从1到n整数中1出现的次数

来源:互联网 发布:rf 910编程器驱动程序 编辑:程序博客网 时间:2024/06/05 19:37

题目描述:输入一个整数n,求从1到n这n个整数中的十进制表示中1出现的次数。例如输入12,从1到12这些整数中包含1的数字有1,10,11,12,因此1共出现了5次。

本题为leetcode、剑指offer、编程之美等众多资料和平台上的经典题目。

其实,仔细思考数字的组成,本题并不是很难。

设该数为[AAA]-X-[BBB],其中我们考察本位数为X
1、本位数大于1,则本位上含有1为:([AAA]+1)*本位进制:000-------AAA
2、本位数为1,则本位上含有1为:([AAA])*本位进制+([BBB]+1)  :000--------AAA-1;000---------BBB
3、本位数小于1,则本位上含有1的个数为([AAA])*本位进制  :000--------AAA-1;

因此有下面的代码:

int countDigitOne(int n) {  //传入数n
       int reminder = 0;
int quotient = 0;
int count=0;
int times=0;
quotient = n / 10;
reminder = n % 10;
times = 1;
while(quotient!=0||reminder!=0)
{
if(reminder > 1)
{
count+=(quotient+1)*(int)(pow(10,times-1)+0.001);//因为pow是double型函数,因此必须转换成int型函数,并且要注意精度控制。
}
else if(reminder==1)
{
count+=quotient*(int)(pow(10,times-1)+0.001)+n%(int)(pow(10,times-1)+0.001)+1;
}
else if(reminder==0)
{
count+=quotient*(int)(pow(10,times-1)+0.001);
}
reminder=quotient%10;
quotient=quotient/10;
times++;
}
return count;
}

1 0