Add Two Numbers

Task

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
Examples :

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

This problem was taken from Leetcode

Solution

The solution:

Java Script

/**
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}
 */
var addTwoNumbers = function(l1, l2) {
	
	doSum = function(a, b, cary) {
		var _cary = 0;
		var sum = a + b + cary;
		if(sum == 10) {
		  sum = 0;
		  _cary = 1;
		}
		else if(sum > 10) {
		  sum = sum - 10;
		  _cary = 1;			
		}
		return  {
			'sum' : sum,
			'cary' : _cary

		}		
	}
		

	var nodeA = l1;
	var nodeB = l2;
	var cary = 0;
	var sum = 0;
	var result = null;
	var lastNode = null;


	while(nodeA != null || nodeB != null) {

		var a = nodeA ?nodeA.val : 0;
		var b = nodeB ?nodeB.val : 0;
		sumResult = doSum(a, b, cary);
		node = new ListNode(sumResult.sum);
		cary = sumResult.cary;

		if(result == null) {
			result = node;
		}
		else {
			lastNode.next = node;
		}
		lastNode = node;

		nodeA = nodeA ? nodeA.next : nodeA;
		nodeB = nodeB ? nodeB.next : nodeB;

	}
	if(cary > 0) {
		node.next = new ListNode(cary);
	}
	return result;
}

Leave a Reply