Power button - programming question 2 - sum of two numbers (java)

Keywords: Java

Topic 2: sum of two numbers

  • Two non empty linked lists are given to represent two non negative integers. Their respective digits are stored in reverse order, and each node can only store one digit.
    If we add the two numbers together, we will return a new linked list to represent their sum. You can assume that neither of these numbers starts with 0 except for the number 0.

java code:

package test1;

import java.util.*;
import java.math.BigInteger;
/*
 * Topic 2: sum of two numbers
 * Two non empty linked lists are given to represent two non negative integers. Their respective digits are stored in reverse order, and each node can only store one digit.
If we add the two numbers together, we will return a new linked list to represent their sum. You can assume that neither of these numbers starts with 0 except for the number 0.

Example:

Input: (2 - > 4 - > 3) + (5 - > 6 - > 4)
Output: 7 - > 0 - > 8
 Reason: 342 + 465 = 807
*/
//node
class ListNode{
	int val;
	ListNode next;
	ListNode(int x) {
		// TODO Auto-generated constructor stub
		val = x;
	}
}


public class addTwoNumbers {

	public static void main(String[] args) {
		//Scanner in = new Scanner(System.in);
		
		ListNode l1 = new ListNode(2);
		ListNode node2 = new ListNode(4);
		ListNode node3 = new ListNode(3);
		l1.next=node2;
		node2.next=node3;
		ListNode l2 = new ListNode(5);
		ListNode node4 = new ListNode(6);
		ListNode node5 = new ListNode(4);
		l2.next=node4;
		node4.next=node5;

//		while(l1!=null){
//			System.out.print(l1.val);
//			l1 = l1.next;
//		}
//		System.out.println("");
//		while(l2!=null){
//			System.out.print(l2.val);
//			l2 = l2.next;
//		}
		ListNode node1 = addTwo(l1,l2);
		
		while(node1!=null){
			System.out.print(node1.val);
			node1 = node1.next;
		}

		//System.out.print("");
		
		
	}
	public static ListNode addTwo(ListNode l1,ListNode l2) {
		ListNode root = new ListNode(0);//Define a root node
		ListNode temp = root;//temp pointer to root node
		int a=0;
		if(l1==null){//If one is an empty linked list, another will be returned
			return l2;
		}
		if(l2==null)
			return l1;
		
		while(l1!=null && l2!=null){
			int sum = (l1.val+l2.val+a)%10;
			a = (l1.val+l2.val+a)/10;
			ListNode node = new ListNode(0);
			node.val=sum;
			//System.out.println(sum);
			
			//root.next = node;
			temp.next = node;
			temp=node;
			l1=l1.next;
			l2=l2.next;
			
			
		}
		if(l1!=null){
			temp.next=l1;
		}else if(l2!=null){
			temp.next = l2;
		}
		if(a==1){
			while (temp.next!=null) {
				int sum = (temp.next.val+a)%10;
				a = (temp.next.val+a)/10;
				temp.next.val=sum;
				
				temp=temp.next;
				
			}
			if(a==1){
				temp.next = new ListNode(1);
			}
			
		}
		
		return root.next;
	}
	

}


Posted by jonny 5ive on Thu, 14 Nov 2019 12:12:42 -0800