涓€銆侀棶棰樿儗鏅?/h2>
褰撴暟瀛楄秴鍑虹紪绋嬭瑷€鍘熺敓鏁存暟鑼冨洿鏃讹紝闇€瑕佺敤閾捐〃鎴栨暟缁?/strong>鏉ヨ〃绀恒€傛湰鏂囨帰璁ㄥ浣曞皢閾捐〃琛ㄧず鐨勫崄杩涘埗澶ф暣鏁拌浆鎹负浠绘剰杩涘埗銆?/p>
褰撴暟瀛楁瀬澶ф棤娉曠敤BigInt鏃讹紝闇€瑕佹ā鎷熸墜宸ラ櫎娉曪細// 閾捐〃琛ㄧず鏁板瓧123: 1 -> 2 -> 3
// 杞簩杩涘埗: 1 -> 1 -> 1 -> 1 -> 0 -> 1 -> 1 (鍗?111011)
// 杞叓杩涘埗: 1 -> 7 -> 3 (鍗?73)
// 杞崄鍏繘鍒? 7 -> B (鍗?B)
浜屻€佺畻娉曟€濊矾
涓夈€佷唬鐮佸疄鐜?/h2>
class ListNode {
val: number | string;
next: ListNode | null = null;
constructor(val: number | string) { this.val = val; }
}
function convertBase(head: ListNode | null, base: number): ListNode | null {
if (!head) return new ListNode(0);
// 姝ラ1锛氶摼琛ㄨ浆鍗佽繘鍒舵暟鍊?
let decimal = 0n; // 浣跨敤BigInt鏀寔澶ф暟
let current = head;
while (current) {
decimal = decimal * 10n + BigInt(current.val as number);
current = current.next;
}
// 鐗规畩鎯呭喌锛氭暟鍊间负0
if (decimal === 0n) return new ListNode(0);
// 姝ラ2锛氳浆鎹负鐩爣杩涘埗
const digits: string[] = [];
const baseN = BigInt(base);
const hexChars = '0123456789ABCDEF';
while (decimal > 0n) {
const remainder = Number(decimal % baseN);
digits.push(hexChars[remainder]);
decimal = decimal / baseN;
}
// 姝ラ3锛氭瀯寤虹粨鏋滈摼琛紙閫嗗簭锛?
const dummy = new ListNode(0);
let tail = dummy;
for (let i = digits.length - 1; i >= 0; i--) {
tail.next = new ListNode(digits[i]);
tail = tail.next;
}
return dummy.next;
}
鍥涖€侀摼琛ㄥ眰闈㈢殑闄ゆ硶锛堣繘闃讹級
// 妯℃嫙 123 梅 2 鐨勮繃绋?
1 梅 2 = 0 浣?1 鈫?璁板綍鍟?锛岃繘浣?
12 梅 2 = 6 浣?0 鈫?璁板綍鍟?
3 梅 2 = 1 浣?1 鈫?璁板綍鍟?锛屼綑鏁?
鍟? 0 -> 6 -> 1 鍗?1锛屼綑鏁?
浜斻€佸鏉傚害鍒嗘瀽
鍏€佸簲鐢ㄥ満鏅?/h2>