Given an integer n
represented as a string, return the smallest good base of n
.
We call k >= 2
a good base of n
, if all digits of n
base k
are 1
's.
Input: n = "13" Output: "3" Explanation: 13 base 3 is 111.
Input: n = "4681" Output: "8" Explanation: 4681 base 8 is 11111.
Input: n = "1000000000000000000" Output: "999999999999999999" Explanation: 1000000000000000000 base 999999999999999999 is 11.
n
is an integer in the range[3, 1018]
.n
does not contain any leading zeros.
import math
class Solution:
def smallestGoodBase(self, n: str) -> str:
n = int(n)
for x in range(math.ceil(math.log2(n)), 1, -1):
l, r = 2, n - 1
while l <= r:
k = (l + r) // 2
if k ** x - 1 == n * (k - 1):
return str(k)
elif k ** x - 1 < n * (k - 1):
l = k + 1
else:
r = k - 1