For an integer n, we call k>=2 a good base of n, if all digits of n base k are 1.
Now given a string representing n, you should return the smallest good base of n in string format.
Example 1:
Input: "13" Output: "3" Explanation: 13 base 3 is 111.
Example 2:
Input: "4681" Output: "8" Explanation: 4681 base 8 is 11111.
Example 3:
Input: "1000000000000000000" Output: "999999999999999999" Explanation: 1000000000000000000 base 999999999999999999 is 11.
Note:
- The range of n is [3, 10^18].
- The string representing n is always valid and will not have leading zeros.
Next challenges:
思路:首先完成字符串到数字的转换,然后对于特定的num,当前的最长的其他进制的表示长度是进制为2时的表示长度,就是log2(num)+1(注意:10..0有t个0,那么10..0=2^t)。那么指数i的遍历区间就是[1,log2(num)+1]。对于当前数的当前指数i,可能的base整数取值是num^(1/(i-1))。
代码:
1 public class Solution { 2 public String smallestGoodBase(String n) { 3 long num = Long.parseLong(n); 4 int maxIndex = (int) (Math.log(num)/Math.log(2) + 1); 5 for(int i = maxIndex; i >= 3; i--) { 6 long base = (long)Math.pow(num, 1.0 / (i - 1)), sum = 1, cur = 1; 7 for(int j = 1; j < i; j++) { 8 sum += (cur *= base); 9 } 10 if(sum == num) return String.valueOf(base); 11 // java中没有无符号数,而且Math.pow(base, i) - 1存在精度问题,例如样例"14919921443713777",结果应该为"496",但是下列语句的结果是"14919921443713776" 12 // if((long)((Math.pow(base, i) - 1) / (base - 1)) == num) return String.valueOf(base); 13 } 14 return String.valueOf(num - 1); 15 } 16 }