天天看點

233. Number of Digit One【H】【33】【再來一遍】

Given an integer n, count the total number of digit 1 appearing in all non-negative integers less than or equal to n.

For example:

Given n = 13,

Return 6, because digit 1 occurred in the following numbers: 1, 10, 11, 12, 13.

Show Hint 

  1. Subscribe to see which companies asked this question

按位算,先算個位數的1 有多少個,再算十位數的,依次往上

寫了好多遍啊。。。。

class Solution(object):
    def countDigitOne(self, n):
        if n < 1:
            return 0

        b = 0
        t = 1
        res = 0

        while t <= n:
            b = n / (t*10)

            tres = b * t

            temp = (n / t)%10
            if temp == 10:
                temp = 1

            if temp == 1:
                tres += n % t + 1

            elif temp > 1:
                tres += t

            res += tres

            #print t,b,tres

            t *= 10

        return  int(res)