Suppose we have an integer n, we call k >= 2 as a good base of n, when all digits of n base k are 1. So if the number n is given as string, we have to return smallest good base of n as string. So if the number is say 121, then the answer will be 3, as 121 in base 3 is 11111.
To solve this, we will follow these steps −
Let us see the following implementation to get better understanding −
class Solution(object): def getSum(self, x, length): mainSum = 0 temp = 1 for i in range(length): mainSum += temp temp *= x return mainSum def check(self, n, length): low = 1 high = n while high >= low: mid = low + (high - low) // 2 mainSum = self.getSum(mid, length) if mainSum == n: return mid elif mainSum > n: high = mid - 1 else: low = mid + 1 return -1 def smallestGoodBase(self, n): n = int(n) for i in range(64, 0, - 1): x = self.check(n, i) if x >= 2: return str(x) return str(n - 1) ob = Solution() print(ob.smallestGoodBase("121"))