forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcount-good-numbers.py
More file actions
33 lines (29 loc) · 767 Bytes
/
count-good-numbers.py
File metadata and controls
33 lines (29 loc) · 767 Bytes
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
# Time: O(logn)
# Space: O(1)
class Solution(object):
def countGoodNumbers(self, n):
"""
:type n: int
:rtype: int
"""
def powmod(a, b, mod):
a %= mod
result = 1
while b:
if b&1:
result = (result*a)%mod
a = (a*a)%mod
b >>= 1
return result
MOD = 10**9 + 7
return powmod(5, (n+1)//2%(MOD-1), MOD)*powmod(4, n//2%(MOD-1), MOD) % MOD
# Time: O(logn)
# Space: O(1)
class Solution2(object):
def countGoodNumbers(self, n):
"""
:type n: int
:rtype: int
"""
MOD = 10**9 + 7
return pow(5, (n+1)//2%(MOD-1), MOD)*pow(4, n//2%(MOD-1), MOD) % MOD