剑指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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章