Using Javascript to subtract large strings

Source: Internet
Author: User

Function subtract (str1, str2 ){
// Alert (a + "-" + B + "=" + (a-B ));
// Subtraction result
Var c = "";
// Debit sign
Var flog = true;
// The length of the subtrahend and subtrahend.
Var I = str1.length-1;
Var j = str2.length-1;
If (j> I ){
Var c = '-' + subtract (str2, str1 );
Return c;
}
If (j = I & str1 <str2 ){
Var c = '-' + subtract (str2, str1 );
Return c;
}
For (; I> = 0; I --, j --){
// Obtain the low position
Var charb = 0;
If (j> = 0 ){
Charb = str2.charAt (j );
}

// Obtain the subtrahend
Var chara = str1.charAt (I );
// If the digit is used
If (flog! = True ){
// If the borrow value is 0
If (chara = 0 ){
// Borrow another one and then subtract one
Flog = false;
Chara = 9;
} Else if (chara-1) <charb ){
// If not, borrow one.
Flog = false;
Chara = 1 + chara-1;
} Else {
Chara = chara-1;

Flog = true;
}
}
// Low position Subtraction
If (chara> = charb ){
C = ''+ (chara-charb) + c;
// Alert ('enough reduction' + c );
} Else {
// If the borrow space is not enough
Var x = 1 + chara-charb;
// Alert (x );
C = ''+ x + c;
Flog = false;
// Alert ('undiminished '+ c );
}
}
// String
Return c;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.