leetcode 483. 最小好进制
用二进制计算位数最长是多少,然后从大到小遍历可能的位数,二分查找“进制数”即可。
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);
}
};
原文地址:https://blog.csdn.net/fks143/article/details/145081783
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!