-
热度指数:1558
时间限制:C/C++ 1秒,其他语言2秒
空间限制:C/C++ 64M,其他语言128M
-
算法知识视频讲解
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.
输入描述:
Each input file contains one test case which gives the positive N (<=230).
输出描述:
For each test case, print the number of 1's in one line.
题目代码: #include<iostream> #include<cstdlib> #include<cstdio> using namespace std; int NumberOf1Between1AndN(int n) { int result=0,sum=0,std=1,i=n; while(i/std){ int temp=i/(std*10); int num_bit=(i%(std*10))/std; if(num_bit==0) sum=temp*std; else if(num_bit==1) sum=temp*std+i%std+1; else sum=(temp+1)*std; result=result+sum; std=std*10; sum=0; } return result; } int main(){ int num=0; scanf("%d",&num); num=NumberOf1Between1AndN(num); printf("%d\n",num); return 0; } 复杂度分析: 从解题思路的分析中可以看出: 其复杂度为输入正整数的n的十进制位数,也就是如果输入的是2位数(10-99) 执行次数为2,为5位数则while的执行次数为5,所以这里这里复杂度为log10(n),即log以10为低b的对数。