1. 大數相加
function addBigNum(a,b){ var res = '', loc = 0; a = a.split(''); b = b.split(''); while(a.length || b.length || loc){ //~~把字符串轉換為數字,用~~而不用parseInt,是因為~~可以將undefined轉換為0,當a或b數組超限,不用再判斷undefined //注意這里的+=,每次都加了loc本身,loc為true,相當於加1,loc為false,相當於加0 loc += ~~a.pop() + ~~b.pop(); //字符串連接,將個位加到res頭部 res = (loc % 10) + res; //當個位數和大於9,產生進位,需要往res頭部繼續加1,此時loc變為true,true + 任何數字,true會被轉換為1 loc = loc > 9; } return res.replace(/^0+/,''); }
2. 大數相乘
function multiplyBigNum(num1, num2) { //判斷輸入是不是數字 if (isNaN(num1) || isNaN(num2)) return ""; let len1 = num1.length, len2 = num2.length; let pos = []; //j放外面,先固定被乘數的一位,分別去乘乘數的每一位,更符合豎式演算法 for (let j = len2 - 1; j >= 0; j--) { for (let i = len1 - 1; i >= 0; i--) { //兩個個位數相乘,最多產生兩位數,index1代表十位,index2代表個位 let index1 = i + j, index2 = i + j + 1; //兩個個位數乘積加上當前位置個位已累積的數字,會產生進位,比如08 + 7 = 15,產生了進位1 let mul = num1[i] * num2[j] + (pos[index2] || 0); //mul包含新計算的十位,加上原有的十位就是最新的十位 pos[index1] = Math.floor(mul / 10) + (pos[index1] || 0); //mul的個位就是最新的個位 pos[index2] = mul % 10; } } //去掉前置0 let result = pos.join("").replace(/^0+/, ""); return result || '0'; }
參考: https://segmentfault.com/a/1190000015979292?utm_source=tag-newest