-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
count-the-number-of-powerful-integers.py
69 lines (63 loc) · 1.75 KB
/
count-the-number-of-powerful-integers.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# Time: O(logf)
# Space: O(1)
# math, combinatorics
class Solution(object):
def numberOfPowerfulInt(self, start, finish, limit, s):
"""
:type start: int
:type finish: int
:type limit: int
:type s: str
:rtype: int
"""
def count(x):
def length(x):
result = 0
while x:
x //= 10
result += 1
return result
result = 0
n = length(x)
base = 10**n
l = n-len(s)
cnt = (limit+1)**l
for i in xrange(l):
base //= 10
curr = x//base%10
cnt //= limit+1
result += (min(curr-1, limit)-0+1)*cnt
if curr > limit:
break
else:
if x%base >= int(s):
result += 1
return result
return count(finish)-count(start-1)
# Time: O(logf)
# Space: O(logf)
# math, combinatorics
class Solution2(object):
def numberOfPowerfulInt(self, start, finish, limit, s):
"""
:type start: int
:type finish: int
:type limit: int
:type s: str
:rtype: int
"""
def count(x):
result = 0
str_x = str(x)
l = len(str_x)-len(s)
cnt = (limit+1)**l
for i in xrange(l):
cnt //= limit+1
result += (min(int(str_x[i])-1, limit)-0+1)*cnt
if int(str_x[i]) > limit:
break
else:
if int(str_x[-len(s):]) >= int(s):
result += 1
return result
return count(finish)-count(start-1)