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 思路:本题思路很值得让人思考,一位一位的进行分析可使时间大为减少,另外需要注意的一点就是当分析的数字为0,为1和大于等于2的情况时应该仔细区分情况。
1 #include <cstdio> 2 #include <iostream> 3 using namespace std; 4 int main(int argc, char *argv[]) 5 { 6 int N; 7 scanf("%d",&N); 8 int sum=0,left=10,right=1; 9 int NN=N; 10 int pt; 11 int now=10; 12 while(NN!=0) 13 { 14 int temleft=N/left; 15 int temright=N%right; 16 pt=NN%10; 17 NN/=10; 18 if(pt==0) 19 { 20 sum+=temleft*right; 21 } 22 else if(pt==1) 23 { 24 sum+=temleft*right+temright+1; 25 } 26 else 27 { 28 sum+=(temleft+1)*right; 29 } 30 left*=10; 31 right*=10; 32 } 33 printf("%d\n",sum); 34 return 0; 35 }
时间: 2024-10-14 00:42:59