京东实习前端笔试 2022年3月19日 问题二分鸡蛋

这道题目思路很简单:
- 要么+1
- 要么/3, /3 的收敛速度远远大于+1,所以优先选择 /3
function t2(
T = 2,
xy = [
[4, 1],
[2, 2],
]
) {
let res = [];
for (let i = 0; i < T; i++) {
let x = xy[i][0];
let y = xy[i][1];
res.push(ttt(x, y));
}
return res;
}
function ttt(x = 4n, y = 1n) {
if (x <= y) { // x 比 y 小,直接返回 y-x
return y - x;
}
let res = 0n;
while (x != y) {
if (x <= y) { // 除以 3 后已经比1小,直接把x加到y
res += y - x;
return res;
}
if (x % 3n == 0n) { // 直接可以整除3,则res++
x = x / 3n;
res++;
} else { // 不能整除3,x加到能被3整除的数 3n-(x%3n) ,则这里 res 增加了 3n-(x%3n) + 1
res += 3n - (x % 3n) + 1n;
x = x / 3n + 1n;
}
}
return res;
}
let T = 2;
let xy = [
[10n ** 18n, 10n ** 18n - 2n],
[10n ** 16n, 10n ** 16n - 1n],
];
// 这里 10^16 超过了 Number.Max_VALUE 必须使用 BigInt
console.log(t2(T, xy).join(" ").replace("n", ""));
// 输出为:
// 666666666666666667 6666666666666668

浙公网安备 33010602011771号