• 主要找规律,用base*round这个主要规律,base代表该位数的权重,round表示该数前面的值(表示在该位循环了多少次)。用weight表示该数值,former表示该数后面的值(只有当weight为1时有用)。
    当weight = 1 时用 base * round+former+1
    当weight = 0 时用 base * round
    当weight > 1 时用 base * round+base
    注意former的计算,用round对base取余计算
    weight计算,用round对10取余
    round每次要 对10除尽
    base每次乘以10
class Solution:
    def NumberOf1Between1AndN_Solution(self, n):
        num, count, former, weight, base = n, 0, 0, 0, 1
        while num != 0:
            weight = num % 10
            former = n % base
            num = num // 10
            if weight > 1:
                count += num * base + base
            elif weight == 1:
                count += num * base + former + 1
            else:
                count += num * base
            base = base * 10
        return count
s = Solution()
print(s.NumberOf1Between1AndN_Solution(13))