https://leetcode.com/problems/smallest-good-base
关于 base 的概念:
Input: "13" Output: "3" Explanation: 13 base 3 is 111.
Input: "4681" Output: "8" Explanation: 4681 base 8 is 11111.
Input: "1000000000000000000" Output: "999999999999999999" Explanation: 1000000000000000000 base 999999999999999999 is 11.
13 = (1 * 3 + 1) * 3 + 1
4681 = (((1 * 8 + 1) * 8 + 1) * 8 + 1) * 8 + 1
用 getResultOfBase 求出这个 base 所能构成的 good base,和目标值比较,二分查找。
public class Solution { public String smallestGoodBase(String n) { Long num = Long.parseLong(n); int times = (int)(Math.log(num) / Math.log(2) + 1); for (int i = times; i >= 2; i--) { Long start = 2L; Long end = (long)Math.pow(num, 1.0 / i); // was num/2, failed case: 2251799813685247 while (start <= end) { Long mid = start + (end - start) / 2; Long target = getResultOfBase(mid, i); int retval = target.compareTo(num); if (retval == 0) { // was target == num, failed case: 3541 return Long.toString(mid); } else if (retval > 0) { end = mid - 1; } else { start = mid + 1; } } } return Long.toString(num - 1); } private Long getResultOfBase(Long base, int times) { Long current = 1L; for (int i = 0; i < times; i++) { current = current * base + 1; } return current; } }