題目描述:
求出任意非負整數區間中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