Skip to content

Instantly share code, notes, and snippets.

@daifu
Created March 15, 2013 04:39
Show Gist options
  • Select an option

  • Save daifu/5167519 to your computer and use it in GitHub Desktop.

Select an option

Save daifu/5167519 to your computer and use it in GitHub Desktop.
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.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
* example:
* Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
* Output: 7 -> 0 -> 8
*/
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
// Start typing your Java solution below
// DO NOT write main() function
return addTwoNumbersHelper(l1, l2, 0);
}
public ListNode addTwoNumbersHelper(ListNode l1, ListNode l2, int carry) {
ListNode node = null;
int sum = 0;
if(l1 == null && l2 == null) {
if(carry > 0) {
node = new ListNode(carry);
return node;
} else {
return null;
}
}
int l1Val = l1 != null? l1.val:0;
int l2Val = l2 != null? l2.val:0;
sum = l1Val + l2Val + carry;
if(sum >= 10) {
carry = 1;
sum -= 10;
} else {
carry = 0;
}
node = new ListNode(sum);
node.next = addTwoNumbersHelper(l1 != null ? l1.next : null,
l2 != null ? l2.next : null,
carry);
return node;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment