题解 | #整数中1出现的次数(从1到n整数中1出现的次数)#
整数中1出现的次数(从1到n整数中1出现的次数)
http://www.nowcoder.com/practice/bd7f978302044eee894445e244c7eee6
遍历所有位,将数分成三段,right x left 当x = 1时, 加上left后面的余数 当x < 1时,直接过 当x > 1时,right+1 个 pow(10,i-1)个1 这样每一位的1都被统计了
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param n int整型
# @return int整型
#
class Solution:
def NumberOf1Between1AndN_Solution(self , n: int) -> int:
# write code here
s = str(n)
l = len(s)
i = l - 1
num = 0
while i >= 0:
x = int(s[i])
if i+1 == l:
right = 0
else:
right = int(s[i+1:])
if s[:i] == '':
left = 0
else:
left = int(s[:i])
base = pow(10, l-1-i)
if x == 1:
num += left * base + right + 1
elif x < 1:
num += left * base
else:
num += (left+1) * base
i -= 1
return num