Andrunevchyn

Andrunevchyn


November 2016
M T W T F S S
 123456
78910111213
14151617181920
21222324252627
282930  

Categories


LeetCode: 2. Add Two Numbers

Andriy AndrunevchynAndriy Andrunevchyn

My first task on LeetCode

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.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

 

package problems.algorithm.twonumbers;

/*
 * 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.
 * 
 * Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8
 */
public class Solution {
	public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
		ListNode result = new ListNode(0);
		add(result, l1, l2);
		System.out.println(result);
		return result;
	}

	private void add(ListNode listNode, ListNode l1, ListNode l2) {

		int val1 = (l1 != null ? l1.val : 0);
		int val2 = (l2 != null ? l2.val : 0);
		int sum = listNode.val + val1 + val2;
		listNode.val = sum % 10;

		int fraction = sum / 10;

		if (fraction != 0) {
			listNode.next = new ListNode(fraction);
		}

		ListNode next1 = l1 != null ? l1.next : null;
		ListNode next2 = l2 != null ? l2.next : null;
		if (next1 != null || next2 != null) {
			listNode.next = new ListNode(fraction);
			add(listNode.next, next1, next2);
		}

	}

	public static void main(String[] args) {
		ListNode l1 = new ListNode(2);
		l1.next = new ListNode(4);
		l1.next.next = new ListNode(3);

		ListNode l2 = new ListNode(5);
		l2.next = new ListNode(6);
		l2.next.next = new ListNode(4);

		Solution solution = new Solution();
		solution.addTwoNumbers(l1, l2);
	}
}

and ListNode class

package problems.algorithm.twonumbers;

public class ListNode {

	int val;
	ListNode next;

	ListNode(int x) {
		val = x;
	}

	@Override
	public String toString() {
		StringBuilder builder = new StringBuilder();
		builder.append(val);
		if (next != null) {
			builder.append("->");
			builder.append(next);
		}
		return builder.toString();
	}
}

 

andriy@andrunevchyn.com

Comments 0
There are currently no comments.