[CrackCode] 2.4 Add two numbers and return the sum as a linked list

You have two numbers represented by a linked list, where each node contains a single digit The digits are stored in reverse order, such that the 1’s digit is at the head of the list Write a function that adds the two numbers and returns the sum as a linked list.
============
Analysis:
1. Transform the first linked list to int number 1.
2. Transform the second linked list to int number 2.
3. Compute the sum of this two number.
4. Transform the result to linked list.
public class Answer {

	public static LinkedListNode solution(LinkedListNode header1, LinkedListNode header2){
		if(header1 == null && header2 == null) return null;
		if(header1 == null) return header2;
		if(header2 == null) return header1;
		
		int number1 = 0;
		int number2 = 0;
		
		while(header1!=null){
			number1 = number1*10+header1.data;
			header1 = header1.next;
		}
		
		while(header2!=null){
			number2 = number2*10+header2.data;
			header2 = header2.next;
		}
		
		int sum = number1+number2;
		LinkedListNode next = null;
		
		if(sum==0){
			next.data = 0;
			next.next = null;
			return next;
		}
		
		while(sum>0){
			LinkedListNode node = new LinkedListNode(0, null, null);
			node.data = sum%10;
			node.next = next;
			sum = sum/10;
			next = node;
		}
		return next;
	}
	
	
	public static void main(String[] args) {
		LinkedListNode list1 = AssortedMethods.randomLinkedList(5, 0, 9);
		LinkedListNode list2 = AssortedMethods.randomLinkedList(4, 0, 9);
		LinkedListNode list3 = solution(list1, list2);
		System.out.println("  " + list1.printForward());		
		System.out.println("+ " + list2.printForward());			
		System.out.println("= " + list3.printForward());	
	}
}

Standard answer of the book:

1. result data = (node1 + node2 + any earlier carry) % 10
2. if node1 + node2 > 10, then carry a 1 to the next addition

3. add the tails of the two nodes, passing along the carry 



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值