JS calculation of the sum of two numbers __ algorithm

Source: Internet
Author: User

Question: Calculates the and of two digits.

Analysis: As we all know, number type of value has an upper limit, if it is two large numbers add sum, you cannot use the simplest + method, you can take two numbers as a string to deal with, starting from the end of the add, pay attention to the number of progressive digits, finally get the added string

Realize:

Arguments A, B are all string positive integers, sum
function Add (A, b) {
	var aLen = a.length,
		blen = b.length,
		maxlen = Alen-blen >= 0 ? Alen:blen,
		num = 0,		//Up-level recursive
		str = ';
	for (var i = 1; I <= maxlen i++) {
		var aval = alen-i >= 0 parseint (A.charat (alen-i)): 0,
			bval = Blen- I >= 0? parseint (B.charat (blen-i)): 0,
			bitval = 0,
			addval = aval + bval + num;
		if (Addval >=) {
			num = parseint (ADDVAL/10);
			Bitval = addval%;
		} else{
			num = 0;
			Bitval = Addval;
		}
		STR + + bitval;
	}
	return Array.prototype.reduceRight.call (str, function (A, b) {return a + B;});
The second way, recursive algorithm

function Add (A, b) {var Aarr = A.split ('). Reverse (), BARR = B.split ("). reverse (); Return (function Addstep (Aarr, BARR, str, num) {var aval = Aarr.length = 0? 0:parseint (Aarr.shift ()), Bval = BAr R.length = = 0? 0:parseint (Barr.shift ()), num = num | | 0, Bitval = 0, Addval = aval + bval + num, str = str | |
		'';
			if (addval >=) {num = parseint (ADDVAL/10);
		Bitval = addval% 10;
			}else{num = 0;
		Bitval = Addval;
		STR + + Bitval; if (Aarr.length = = 0 && barr.length = 0) {console.log (Array.prototype.reduceRight.call (str, function (A, b) {RE
		Turn A + b;});
		}else{Addstep (Aarr, BARR, str, num); }}) (Aarr, BARR, ', 0)} 

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.