其他分享
首页 > 其他分享> > LC483. Smallest Good Base

LC483. Smallest Good Base

作者:互联网

对于给定的正整数n,如果n的k(k >= 2) 进制数的所有数位全为1,则称k是n的一个好进制。

以字符串形式给出n,以字符串形式返回n的最小好进制。

分析:最差的情况,n的n-1进制数为11,n的二进制有$log_{2}n+1$位数,位数越多,进制越小,从$k = log_{2}n+1$位开始查找,

用二分查找求$b + b^1 + b^2 + ... + b^{(k - 1)} = n$的解即可,二分初始区间可以取$[2, n^{\frac{1}{k-1}}]$

class Solution {
public:
    typedef unsigned long long uff;
    string smallestGoodBase(string n) {
        uff num = (uff)stoll(n);
        int maxlen = log(num) / log(2) + 1;
        for (int k = maxlen; k >= 3; --k) {
            uff val = pow(num, 1.0 / (k - 1));
            uff res = bs(val, num, k);
            if (res != 0) return to_string(res);
        }
        return to_string(num - 1);
    }
    
    uff bs(uff val, uff t, int k) {
        uff l = 2, r = val, mid;
        while (l <= r) {
            mid = l + (r - l) / 2;
            uff sum = 1, cur = 1;
            for (int i = 1; i < k; ++i) {
                cur *= mid;
                sum += cur;
            }
            if (sum == t) return mid;
            else if (sum < t) l = mid + 1;
            else r = mid - 1;
        }
        return 0;
    }
};

 

标签:Base,Good,num,进制,val,uff,Smallest,string,log
来源: https://www.cnblogs.com/betaa/p/12529768.html