题目描述:
求出任意非负整数区间中1出现的次数(从1 到 n 中1出现的次数)。
思路:
贴一个我觉得最优雅的解法,比剑指offer书的解法要好。
代码:
# -*- coding:utf-8 -*-
class Solution:
def NumberOf1Between1AndN_Solution(self, n):
# write code here
if n<1:
return 0
count = 0
base = 1
round = n
while round>0 :
weight = round%10
round /= 10
count += round*base
if weight==1:
count+=(n%base)+1
elif weight>1:
count += base
base*=10
return count