Description:
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
My answer:
#include <iostream>
using namespace std;
int main(){
int n;
cin >> n;
int left, right, now, time = 1;
//time代表当前位所在的位
int answer = 0;
while(n / time){//如果还没有遍历到最高位
right = n % time;
left = n / (time * 10);
now = (n / time) % 10;
if(now == 0){
answer += left * time;
} else if(now == 1){
answer += left * time + right + 1;
} else {
answer += (left + 1) * time;
}
time *= 10;
}
cout << answer << endl;
return 0;
}