在JavaScript中找到最小的良好基础
良好的基础
对于整数num,如果numbasek的所有数字均为1,则称k(k>=2)为num的良好基数。
例如:13的基数3是111,因此3是num=13的良好基数
问题
我们需要编写一个JavaScript函数,该函数采用代表数字的字符串str作为唯一参数。该函数应返回尽可能小的数字的字符串表示形式,这是str的良好基础。
例如,如果函数的输入为-
const str = "4681";
那么输出应该是-
const output = "8";
输出说明:
因为4681的基数8是11111
示例
为此的代码将是-
const str = "4681"; const smallestGoodBase = (n = '1') => { const N = BigInt(n), bigint2 = BigInt(2), bigint1 = BigInt(1), bigint0 = BigInt(0) let maxLen = countLength(N, bigint2) //最多maxLen1s的结果 const findInHalf = (length, smaller = bigint2, bigger = N) => { if (smaller > bigger){ return [false]; }; if (smaller == bigger) { return [valueOf1s(smaller, length) == N, smaller] }; let mid = (smaller + bigger) / bigint2; let val = valueOf1s(mid, length); if(val == N){ return [true, mid]; }; if (val > N){ return findInHalf(length, smaller, mid - bigint1); }; return findInHalf(length, mid + bigint1, bigger); }; for (let length = maxLen; length > 0; length--) { let [found, base] = findInHalf(length); if(found){ return '' + base; } }; return '' + (N - 1); function valueOf1s(base, lengthOf1s) { let t = bigint1 for (let i = 1; i < lengthOf1s; i++) { t *= base t += bigint1 } return t } function countLength(N, base) { let t = N, len = 0 while (t > bigint0) { t /= base len++ } return len } }; console.log(smallestGoodBase(str));输出结果
控制台中的输出将是-
8