题目描述:
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
代码长度限制
16 KB
时间限制
400 ms
内存限制
64 MB
题目大意:
给出一个n,求从0到n一共出现几个1
解题思路:
这题还是有点复杂的,看了一下别人的代码,基本思路是一位一位考虑,也就是计算这一位为1的数有几个,用now表示当前位的值,left为左边的数字,right为右边的数字,a为当前位的位数,以3105为例:
- 当now>=2时,比如分为310 5 0,此时now=5也就是说可以取(0~310)1,这些数当前位为1,res+=(left+1)*a
- 当now==1时,比如3 1 05,此时1后面的数不能取全到a,只能取到right,所以res+=left*a+right+1
- 当now==0时,比如31 0 5,此时只能当(0~30)时当前位才能取1,所以res+=left*a
Python3代码:
n = int(input())
left,right,now,a = 0,0,0,1
res = 0
while n // a :
left = n // (a*10)
right = n % a
now = n // a % 10
if now == 0 : res += left * a
elif now == 1 : res += left * a + 1 + right
else : res += (left+1) * a
a *= 10
print(res)