[LeetCode] Smallest Good Base

483. Smallest Good Base

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.

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
class Solution {
unsigned long long helper(long long n, long long d) {
unsigned long long l = 1, r = pow(n, 1.0 / d) + 1;
while(l <= r) {
unsigned long long mid = l + (r - l) / 2;
unsigned long long sum = 0;
for(unsigned long long i = 0, mul = 1; i <= d; i++, mul *= mid) {
sum += mul;
}
if(sum == n) return mid;
if(sum > n) r = mid - 1;
else l = mid + 1;
}
return 0;
}
public:
string smallestGoodBase(string n) {
unsigned long long num = stoll(n);
for(int i = log2(num); i >= 1; i--) {
unsigned long long res = helper(num, i);
if(res) return to_string(res);
}
return to_string(num - 1);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/29/PS/LeetCode/smallest-good-base/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.