1049 Counting Ones
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
#include<iostream>
using namespace std;
//书P1049
//例如数字30710,从个位数往前看,个位数记为第一位,最前面一位数字为第五位
//一位一位的来取1
//第一位为0 <1,左边有四位3071,右边零位,仅在前四位为0000-3070时,第一位才可取到1,此时有3071*1种情况
//第二位为1=1,左边有三位307,右边有一位(1)前面三位000-306,右边一位可以取任意0-9 此时有307*10种情况,10是指0-9(2)当高位为307时,就一种情况
int main(){
int n;
cin>>n;
int left,now,right,a=1,ans=0;
while(n/a!=0){
left=n/(a*10);
now=n/a %10;
right=n%a;
if(now==0) ans+=left*a;
else if(now==1) ans+=left*a+right+1;
else ans+=(left+1)*a;
a*=10;
}
cout<<ans<<endl;
}