-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path2999-count-the-number-of-powerful-integers.py
More file actions
47 lines (40 loc) · 1.19 KB
/
2999-count-the-number-of-powerful-integers.py
File metadata and controls
47 lines (40 loc) · 1.19 KB
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
# time complexity: O(log(finish))
# space complexity: O(log(finish))
class Solution:
def numberOfPowerfulInt(
self, start: int, finish: int, limit: int, s: str
) -> int:
startStr = str(start - 1)
finishStr = str(finish)
return self.calculate(finishStr, s, limit) - self.calculate(startStr, s, limit)
def calculate(self, x: str, s: str, limit: int) -> int:
if len(x) < len(s):
return 0
if len(x) == len(s):
return 1 if x >= s else 0
suffix = x[len(x) - len(s):]
count = 0
preLen = len(x) - len(s)
for i in range(preLen):
if limit < int(x[i]):
count += (limit + 1) ** (preLen - i)
return count
count += int(x[i]) * (limit + 1) ** (preLen - 1 - i)
if suffix >= s:
count += 1
return count
start = 1
finish = 6000
limit = 4
s = "124"
print(Solution().numberOfPowerfulInt(start, finish, limit, s))
start = 15
finish = 215
limit = 6
s = "10"
print(Solution().numberOfPowerfulInt(start, finish, limit, s))
start = 1000
finish = 2000
limit = 4
s = "3000"
print(Solution().numberOfPowerfulInt(start, finish, limit, s))