Created
November 14, 2017 16:54
-
-
Save shailrshah/abef5529f0df78d918d2bc333f3c8a49 to your computer and use it in GitHub Desktop.
You are given two non-empty linked lists representing two non-negative integers. 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. You may assume the two numbers do not contain any leading zero, except the number 0 itself. Input: (2 -> 4 -> 3) + (5 -> 6 -> 4…
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public ListNode addTwoNumbers(ListNode l1, ListNode l2) { | |
if(l1 == null && l2 == null) return null; | |
ListNode help1 = l1, help2 = l2, dummyHead = new ListNode(0), help3 = dummyHead; | |
int c = 0; | |
while(help1 != null || help2 != null) { | |
int a = help1 == null ? 0 : help1.val; | |
int b = help2 == null ? 0 : help2.val; | |
int sum = a + b + c; | |
help3.next = new ListNode(sum % 10); | |
c = sum / 10; | |
help1 = help1 == null ? help1: help1.next; | |
help2 = help2 == null ? help2: help2.next; | |
help3 = help3.next; | |
} | |
if(c != 0) | |
help3.next = new ListNode(c); | |
return dummyHead.next; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment