劍指offer全集詳解python版——整數中1出現的次數

題目描述:
求出任意非負整數區間中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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章