483. Smallest Good Base

题目链接:https://leetcode.com/problems...

enumerate,但是不是结果,而是幂。方法特别巧妙,另外求幂的和还可以优化用快速幂来求。知道幂之后,根据逼近法,可以得到base:k = logm(n) = (long) (pow(n, 1/m)) = (long) (log(n) / log(m)),幂的最大值是min(log2(n), 64),当然这个是m>1的时候。注意求pow(base, m)不能直接用pow因为java里面double和long的转换过程中会丢失信息,所以要用乘来做。
参考这个博客:
http://bookshadow.com/weblog/...

public class Solution {
    public String smallestGoodBase(String n) {
        long num = Long.valueOf(n);
        
        for(int m = Math.min((int) (Math.pow(num, 0.5)), 64); m > 1; m--) {
            // k = logm(num)
            long k = (long) Math.pow(num, 1.0 / m);
            if(isGoodBase(num, k, m)) return String.valueOf(k);
        }
        return String.valueOf(num - 1);
    }
    
    private boolean isGoodBase(long num, long base, int m) {
        long sum = num;
        long val = 1;
        // calculate k^0, k^1,  ..., k^m
        for(int i = 0; i <= m; i++) {
            sum -= val;
            val *= base;
        }
        return sum == 0;
    }
}

另外题目标签是binary search,应该是对k的取值可以用binary search来找。


lulouch13
13 声望6 粉丝