After writing a large integer addition to the previous blog post, I simulated the algorithm of the previous blog post, and realized the large integer subtraction.
Large integer subtraction is slightly more complex than addition. Because there are a few things to consider:
1. Subtract two numbers, which may result in positive, negative and 03 cases;
2. There will be borrow, and also consider whether there is borrow at the highest level.
The implementation code is as follows:
functionsubString (A, b) {//complement strings A and b to equal lengths while(A.length <b.length) {a= ' 0 ' +A; } while(B.length <a.length) {b= ' 0 ' +b; } //Res Saves the result, C is used to identify the case with or without borrow varRes= ', c=0; A= A.split (' '); b= B.split (' '); while(a.length) {varNUM1 = ~ ~A.pop (); varNum2 = ~ ~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 } //judge whether the highest bit has borrow, if there is borrow, the result is negative if(A.length = = 0 &&c) {Res= '-' +Res}} Res= Res.replace (/^0+/, "); //determine if the final result is 0 if(res = = = ") {res= 0; } returnRes;}
JavaScript implements large integer subtraction