Skip to content

Commit 6d87a18

Browse files
committed
Runtime: 3 ms (Top 73.58%) | Memory: 6.3 MB (Top 42.92%)
1 parent 9be8f82 commit 6d87a18

File tree

1 file changed

+6
-5
lines changed

1 file changed

+6
-5
lines changed
Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,18 @@
1+
// Runtime: 3 ms (Top 73.58%) | Memory: 6.3 MB (Top 42.92%)
12
class Solution {
23
public:
34
string smallestGoodBase(string n) {
45
string ans;
56
long long nn = stol(n);
6-
7+
78
// since n<1E18, the largest possible number of digits is 62.
89
for (int i=62;i>2;i--){
910
// Since n = k^i-1 + k^i-2 + ... + k + 1, a good estimate of k is pow(n, 1/(i-1))
1011
long long k = pow(nn,1.0/(i-1));
1112
if (k==1) continue;
12-
13+
1314
long long sum = 1,kk=1;
14-
15+
1516
// Calculate the sum of i-ones base k. Although we have a direct approach using the formula of geometric series sum, n = (k^i - 1)/(k-1), but this approach has two issues: 1) k^i may be larger than LONG_MAX; 2) the pow() function returns a float number which only has 15 decimal digits precision, and not suitable for calculation of 18 digit int.
1617
for (int j=1;j<i;j++){
1718
kk*=k;
@@ -20,8 +21,8 @@ class Solution {
2021

2122
if (sum==nn) return to_string(k);
2223
}
23-
24+
2425
// We always have a trivial solution n-1. The number is 2 digits base (n-1);
2526
return to_string(nn-1);
2627
}
27-
};
28+
};

0 commit comments

Comments
 (0)