Skip to content

Instantly share code, notes, and snippets.

@fever324
Last active August 29, 2015 14:22
Show Gist options
  • Select an option

  • Save fever324/df088e1a4b4032b6b5e1 to your computer and use it in GitHub Desktop.

Select an option

Save fever324/df088e1a4b4032b6b5e1 to your computer and use it in GitHub Desktop.
Add two numbers
/*
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
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int carry = 0;
ListNode head = l1;
ListNode tail = l1;
while(l1 != null && l2!= null) {
tail = l1;
int newL1 = (l1.val + l2.val + carry) % 10;
carry = (carry + l1.val + l2.val) / 10;
l1.val = newL1;
l1 = l1.next;
l2 = l2.next;
}
if (carry == 0) {
if (l2 != null) {
tail.next = l2;
}
return head;
} else {
if (l2 == null) {
while(l1 != null & carry != 0) {
tail =l1;
int newL1 = (l1.val + carry) % 10;
carry = (l1.val + carry) / 10;
l1.val = newL1;
l1 = l1.next;
}
} else if (l1 == null) {
tail.next = l2;
while(l2 != null & carry != 0) {
tail = l2;
int newL1 = (l2.val + carry) % 10;
carry = (l2.val + carry) / 10;
l2.val = newL1;
l2 = l2.next;
}
}
if(carry != 0) {
tail.next = new ListNode(carry);
}
}
return head;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment