www.fatihkabakci.com

Personal Website and Computer Science TUR EN

Interview Question Add Two Numbers

Last update: 11/8/2016 2:47:00 AM

Solution by Fatih KABAKCI

The problem is to add digits in the same order in two linked lists, by creating a new linked list then returning it. The following problem has been published on LeetCode.com. The solution has been provided below as well.

Problem #2- Add Two Numbers

Description: You are given two linked lists representing two non-negative numbers. 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.

Difficulty: Medium

Solution in Java

/**
 * 
 * @author fkabakci
 * Problem Description: You are given two linked lists representing two non-negative numbers. 
 * 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
   
   Input: (0 -> 1) + (0 -> 1 -> 2)
   Output: 0 -> 2 -> 2
   
   Input: () + (0 -> 1)
   Output: 0 -> 1
   
   Input: (9 -> 9) + (1)
   Output: 0 -> 0 -> 1
   
   Input: (9 -> 9) + (9 -> 9)
   Output: 8 -> 9 -> 1
   
   Solution:
   
   First, annex the carry value too into the sum, which is collection of two digits in the same order.
   Then, update new carry value until end of the node.
 */

class ListNode {
	int val;
	ListNode next;

	public ListNode(int x) {
		val = x;
	}

	public ListNode(int... vals) {
		if (vals.length > 1) {
			ListNode t = this;
			int i;
			for (i = 0; i < vals.length - 1; i++) {
				t.val = vals[i];
				t.next = new ListNode(0);
				t = t.next;
			}
			t.val = vals[i];
		}
	}

	public void print() {
		ListNode t = this;
		while (t != null) {
			System.out.print(t.val + "->");
			t = t.next;
		}
		System.out.println();
	}
}

public class AddTwoNumbers {
	public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
		ListNode l3 = new ListNode(0);
		ListNode tl1 = l1, tl2 = l2, tl3 = l3;

		int carry = 0;
		while (tl1 != null || tl2 != null) {
			int digit1 = (tl1 != null) ? tl1.val : 0;
			int digit2 = (tl2 != null) ? tl2.val : 0;
			int sum = carry + digit1 + digit2;
			carry = sum / 10;
			tl3.next = new ListNode(sum % 10);
			tl3 = tl3.next;
			if (tl1 != null)
				tl1 = tl1.next;
			if (tl2 != null)
				tl2 = tl2.next;
		}

		if (carry == 1) {
			tl3.next = new ListNode(carry);
		}
		return l3.next;
	}

	public static void main(String[] args) {

		ListNode l1 = new ListNode(2, 4, 3);
		ListNode l2 = new ListNode(5, 6, 4);
		ListNode l3 = addTwoNumbers(l1, l2);
		l3.print();

		ListNode l21 = new ListNode(0, 1);
		ListNode l22 = new ListNode(0, 1, 2);
		ListNode l23 = addTwoNumbers(l21, l22);
		l23.print();

		ListNode l31 = new ListNode();
		ListNode l32 = new ListNode(0, 1);
		ListNode l33 = addTwoNumbers(l31, l32);
		l33.print();

		ListNode l41 = new ListNode(9, 9);
		ListNode l42 = new ListNode(1);
		ListNode l43 = addTwoNumbers(l41, l42);
		l43.print();

		ListNode l51 = new ListNode(9, 9);
		ListNode l52 = new ListNode(9, 9);
		ListNode l53 = addTwoNumbers(l51, l52);
		l53.print();
	}
}

We basically annex the carry value too into the sum, which is collection of two digits in the same order. Then, we update new carry value. Otherwise, we only add sum of two digits into the node.

The algorithm time complexity is O(max(l1, l2)) because whichever is larger than the other one, we travel through the loop as many times as number of elements in larger linked list. Algorithm space complexity is also same as time. We also create nodes as many as number of loop cycle.

There has been no comment yet

Name:


Question/Comment
   Please verify the image




The Topics in Computer Science

Search this site for





 

Software & Algorithms

icon

In mathematics and computer science, an algorithm is a step-by-step procedure for calculations. Algorithms are used for calculation, data processing, and automated reasoning.

Programming Languages

icon

A programming language is a formal constructed language designed to communicate instructions to a machine, particularly a computer. It can be used to create programs to control the behavior of a machine. Java,C, C++,C#

Database

icon

A database is an organized collection of data. The data are typically organized to model aspects of reality in a way that supports processes requiring information.

Hardware

icon

Computer hardware is the collection of physical elements that constitutes a computer system. Computer hardware refers to the physical parts or components of a computer such as the monitor, memory, cpu.

Web Technologies

icon

Web development is a broad term for the work involved in developing a web site for the Internet or an intranet. Html,Css,JavaScript,ASP.Net,PHP are one of the most popular technologies. J2EE,Servlet, JSP,JSF, ASP

Mobile Technologies

icon

Mobile application development is the process by which application software is developed for low-power handheld devices, such as personal digital assistants, enterprise digital assistants or mobile phones. J2ME

Network

icon

A computer network or data network is a telecommunications network that allows computers to exchange data. In computer networks, networked computing devices pass data to each other along data connections.

Operating Systems

icon

An operating system is software that manages computer hardware and software resources and provides common services for computer programs. The OS is an essential component of the system software in a computer system. Linux,Windows

Computer Science

icon

Computer science is the scientific and practical approach to computation and its applications.A computer scientist specializes in the theory of computation and the design of computational systems.