JavaScript實現大整數減法
阿新 • • 發佈:2018-08-14
split -h lse class 而且 代碼 時有 -c and
繼上一篇博文寫了大整數加法之後,我又模擬上篇博文的算法,自己實現了大整數減法。
大整數減法相對於加法來說,稍微復雜一點。由於要考慮一些情況:
1. 兩個數相減,可能會出現結果為正、負和0三種情況;
2. 會出現借位的情況,而且還要考慮最高位時有沒有借位。
實現代碼如下:
function subString(a,b) { //將字符串a和b補全成同等長度 while (a.length < b.length){ a = ‘0‘ + a; } while (b.length < a.length){ b = ‘0‘ + b; }//res保存結果,c用來標識有無借位的情況 var res=‘‘, c=0; a = a.split(‘‘); b = b.split(‘‘); while (a.length) { var num1 = ~~a.pop(); var num2 = ~~b.pop(); if (num1 >= num2){ c = num1 - num2 - c; res = c + res; c = false; }else { c= num1 + 10 - num2 - c; res = c + res; c = true } //判斷最高位有無借位,若有借位,則說明結果為負數 if (a.length === 0 && c){ res = ‘-‘ + res } } res = res.replace(/^0+/,‘‘); //判斷最後的結果是否為0 if (res === ‘‘){ res = 0; } return res; }
JavaScript實現大整數減法