leetcode 483. 最小好进制

题目:483. 最小好进制 - 力扣(LeetCode)

用二进制计算位数最长是多少,然后从大到小遍历可能的位数,二分查找"进制数"即可。

cpp 复制代码
class Solution {
public:
    string smallestGoodBase(string n_str) {
        uint64_t n = 0;
        for (int i = 0; i < n_str.length(); i++) {
            n = n * 10 + n_str[i] - '0';
        }
        int max = 1;
        uint64_t t = 2;
        while (t <= n / 2) {
            ++max;
            t *= 2;
        }
        ++max;
        uint64_t ret = n - 1;
        uint64_t l, r, m;
        uint64_t a;
        bool invalid;
        for (int i = max; i > 1; i--) {
            l = 2;
            r = n / i;
            while (l <= r) {
                m = (l + r) / 2;
                t = 1;
                a = 1;
                invalid = false;
                for (int j = 0; j < i; j++) {
                    if (a <= (n - t) / m) {
                        a *= m;
                        t += a;
                    } else {
                        invalid = true;
                        break;
                    }
                }
                if (!invalid && t == n) {
                    ret = m;
                    break;
                }
                if (invalid) {
                    r = m - 1;
                } else {
                    l = m + 1;
                }
            }
            if (ret != n - 1) {
                break;
            }
        }
        
        return to_string(ret);
    }
};
相关推荐
To_OC14 小时前
LC 128 最长连续序列:别上来就排序,O (n) 解法才是这题的灵魂
javascript·算法·leetcode
To_OC3 天前
LC 49 字母异位词分组:想到哈希表很简单,选对 key 才是精髓
javascript·算法·leetcode
To_OC4 天前
LC 1 两数之和:面试第一道必考题,暴力解法直接被面试官 pass
javascript·算法·leetcode
想吃火锅100510 天前
【leetcode】121.买卖股票的最佳时机js/c++
算法·leetcode·职场和发展
凌波粒10 天前
LeetCode--491.递增子序列(回溯算法)
数据结构·算法·leetcode
退休倒计时10 天前
【每日一题】LeetCode 146. LRU 缓存 TypeScript
算法·leetcode·缓存·typescript
小欣加油10 天前
leetcode3612 用特殊操作处理字符串I
数据结构·c++·算法·leetcode·职场和发展
凌波粒10 天前
LeetCode--90.子集II(回溯算法)
数据结构·算法·leetcode
凌波粒10 天前
LeetCode--46.全排列(回溯算法)
数据结构·算法·leetcode
吃着火锅x唱着歌10 天前
LeetCode 2530.执行K次操作后的最大分数
数据结构·算法·leetcode