1049. Counting Ones (30)
The task is simple: given any positive integer N, you are supposed to count the total number of 1’s in the decimal form of the integers from 1 to N. For example, given N being 12, there are five 1’s in 1, 10, 11, and 12.Input Specification:
Each input file contains one test case which gives the positive N (<=230).
Output Specification:
For each test case, print the number of 1’s in one line.
Sample Input:
12
Sample Output:
5
分析:这道题就是求1到n之间有的数字里面有多少次出现1,那我们就一位一位判断,left表示当前为左边的所有,right表示当前位右边的所有,每次去判断now位是否是1的时候,和左边右边没有关系,他们能随便取值,不会出现重复,那么当前的这一位的情况now:
1.now = 0 : 那么 ans += left * a; 因为now=0说明now位只有在left从0~left-1的时候会产生1,所以会产生left次,再看右边,右边可以去0~a的任意值,所以有a个
2.now = 1 : ans += left * a + right + 1;now = 1的时候就要比上一步多加一个当now为1的时候右边出现0~right个数导致的now为1的次数
3.now >= 2 : ans += (left + 1) * a;now大于等于2就左边0~left的时候会在now位置产生1,所以会产生left次,同样右边也是取0~a的任意值
最后想说的是这道题求的是1出现的次数,不是包含1数的个数,所以11这种算2.。。。。。好坑
#include <cstdio>
using namespace std;
int main ()
{
int n , left = 0 , right = 0 , a = 1 , now = 1 , result = 0;
scanf_s ("%d" , &n);
while (n / a)
{
left = n / (a * 10) , now = n / a % 10 , right = n % a;
if (now == 0)
result += left * a;
else if (now == 1)
result += left * a + right + 1;
else
result += (left + 1) * a;
a = a * 10;
}
printf ("%d" , result);
return 0;
}