1049. Counting Ones (30)
时间限制
100 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue
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:12Sample Output:
5
从个位数开始,计算每个位上的1出现的可能,a表示当前位的数值,即1、10、100.....计算的方法:
1. 当前位为0,出现次数为 左边的值*a
2. 当前位为1,出现次数为 左边的值*a + 右边的值 + 1
3. 当前位大于1,出现次数为 (左边的值 + 1)*a
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <map>
#include <set>
#include <string>
#include <string.h>
using namespace std;
const int MAX=1e5+10;
int main(){
int n, a=1, left, value, right, sum=0;
scanf("%d", &n);
while(n/a){
left = n /(10 * a);
right = n % a;
value = n / a % 10;
if(value==0) sum += left * a;
else if(value==1) sum += left * a + right + 1;
else sum += (left + 1) * a;
a *= 10;
}
printf("%d\n", sum);
cin>>n;
return 0;
}