JavaScript fun: Add a large integer string

Source: Internet
Author: User
Many languages provide native support for adding two large integer strings. For example, Java provides the BigInteger class, and JS does not support this, so we have to rely on our own implementation. Many languages provide native support for adding two large integer strings.

For example, Java provides the BigInteger class, and JS does not support this, so we have to rely on our own implementation.

The following string addition function receives two string parameters and returns the result after they are added. It is also a string.

The main idea is to add and carry by bit, and there are a lot of details to consider when implementing it.

Function sumStrings (a, B) {// alignment a and B by adding zero // if a is shorter than B, then fill a with zero while (. length <B. length) {a = "0" + a;} // If B is shorter than a, then the while (B. length <. length) {B = "0" + B;} // whether the input var addOne = 0; // result array var result = []; // Add for (var I =. length-1; I> = 0; I --) {var c1 =. charAt (I)-0; var c2 = B. charAt (I)-0; var sum = c1 + c2 + addOne; // if the number is greater than 9, carry if (sum> 9) {result. unshift (sum-10); addOne = 1;} else {res Ult. unshift (sum); addOne = 0 ;}// handle the following situations: // "99" + "11" => "110" // It still needs to carry if (addOne) {result. unshift (addOne);} // handle the following situations // "01" + "01" => "2" // instead of "02 ", so remove the first "0" if (! Result [0]) {result. splice (0, 1);} return result. join ("");}

The above is the JavaScript interesting question: the content of adding a large integer string. For more information, see PHP Chinese Network (www.php1.cn )!

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.