Wins the offer - Number 1

Title Description

Calculated the number of integer of 1 to 13 1 arise, and calculates the number of times an integer from 100 to 1300 in 1 occur? To this end he especially counted about 1 to 13 contains the digits 1 has 1,10,11,12,13 therefore appear a total of six times, but for the problem behind him Meizhe. ACMer hope you will help him, and the problem is more generalized, the number of non-negative integer in the range 1 appears (the number of occurrences from 1 to n. 1) can quickly find any.

Thinking 

Divided into bits, ten, one hundred, one thousand .... specifically how much, see n number of sizes.

We first calculate 0-9; 0-99; 0-999 ... number 1.. Then split n

For example, a number of 4653, split into:

Number 4 000-999 thousandths + 1: -: one thousand [40000000] 

One hundred: [4001--4653]: thousandth not 1, the equivalent of looking for 0 - 653 in the number 1, cycle

# -*- coding:utf-8 -*-
import collections

class Solution:
    def NumberOf1Between1AndN_Solution(self, n):
        if n==0:
            return  0
        
        x = 10
        num = collections.defaultdict(lambda:0)
        while n//x >0:
            num[x] = 10*num[x/10] + x//10    # 0-9 ; 00-99
            x*=10
        x //= 10
        ans = 0
        while n>0 and x >=10:
            if n//x >=2:
                ans += (n//x)* num[x] + x  # 4563 0-4000 + 563 
                # 4000: 0 - 999 1000 - 1999 2000 -2999 3000-3999
            else:
                ans += (n//x)* num[x] + n%x+1 # 1003 0-999 1000 - 1003
            n %= x     # 3
            x //= 10   # 1
        if n >=1:
            ans += 1
        return ans
            

 

Published 82 original articles · won praise 2 · Views 4359

Guess you like

Origin blog.csdn.net/qq_22498427/article/details/104771813