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
题目大意:给出一个数n,数出从0-n之间的数共有多少个1。
解题思路:数学问题,有点小麻烦,一位一位分析。
假定这个数a1a2a3...an,最后一位一一分析,我们现在分析第 i 位。我们计算每一位会出现1的次数,(left)ai(right)。分三种情况讨论:
ai为0的时候,如出现1,只有可能是左边为0-(left-1),总数还要乘以10^(right的位数);
ai为1的时候,如出现1,除了上述情况,还要加上在左边为left的时候,ai=1的情况,但是这种情况总数只要用1*right次;
ai>1的时候,如出现1,那么出现1则可能是左边0-left,总数乘以10^(right的位数)。
#include<vector>
#include<iostream>
#include<cstdio>
using namespace std;
int main(){
int n,a=1;
cin>>n;
int sum=0,left=0,right=0,mid=0;
while(n/a){
left=n/(a*10);
right=n%a;
mid=n/a%10;
if(mid==0)
sum+=left*a;
else if(mid==1)
sum=sum+left*a+right+1;
else
sum+=(left+1)*a;
a*=10;
}
printf("%d",sum);
system("pause");
}