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
题目大意
给定一个数字N,求从1-N的数字中,1总共出现了几次
分析
这是一道逻辑题。
使用result存储最后的答案,a存储当前的个、十、百、千……使用left表示左边的字符表示的数字,right表示右边的字符表示的数字。
从各位开始遍历,判断当前位置的字符:
1> 0 则在当前位置可以出现1的次数为left * a次。
2> 1 则在当前位置可以出现1的次数为left * a + right + 1次
3> 其他 则在当前位置出现1 的次数为(left+1)*a
是不是有些玄学?接下来以123为例进行演示。
1>当前处于个位,当前数字为3.只有1、11、21、31……121总共有13个数字的会在这里出现1.而像11、111这样1出现了好几次的数字,因为会在十位、百位的计算中被算进去。所以依然是遵循题意,计算了1的出现次数的。此时result更新为13,a更新为10.
2>当前处于十位,当前数字为2.只有10-19,110-119总共20个数字会在这里出现1.更新result为33,更新a为100.
3>当前处于百位。当前数字为1.只有100-123总共24个数字会在这个地方出现1.因此更新result为57。更新a为1000
4>循环结束,输出57.
python实现
def main():
n = input()
result, a = 0, 1
for x in range(1, len(n) + 1):
index = len(n) - x
if n[index] == '0':
left = n[:index] if n[:index] !='' else 0
result += int(n[:index]) * a
elif n[index] == '1':
left = n[:index] if n[:index] !='' else 0
right = n[index+1:] if n[index+1:] != '' else 0
result += int(left)*a + int(right) +1
else:
left = n[:index] if n[:index] !='' else 0
result += (int(left)+1)*a
a *= 10
print(result)
if __name__ == "__main__":
main()