京東實習前端筆試 2022年3月19日 問題二分雞蛋
阿新 • • 發佈:2022-03-20
這道題目思路很簡單:
- 要麼+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