-
-
Save InterviewBytes/1a7e71c0377201d04f2de450601e6294 to your computer and use it in GitHub Desktop.
LinkedLists - Add two numbers
This file contains 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
package com.interviewbytes.linkedlists; | |
class ListNode { | |
int val; | |
ListNode next; | |
ListNode(int x) { | |
val = x; | |
} | |
} | |
public class AddTwoNumbers { | |
public ListNode addTwoNumbers(ListNode l1, ListNode l2) { | |
int carry = 0; | |
ListNode sentinel = new ListNode(0); | |
ListNode current = sentinel; | |
while (l1 != null || l2 != null) { | |
int a = 0; | |
int b = 0; | |
if (l1 != null) { | |
a = l1.val; | |
l1 = l1.next; | |
} | |
if (l2 != null) { | |
b = l2.val; | |
l2 = l2.next; | |
} | |
int sum = a + b + carry; | |
current.next = new ListNode(sum % 10); | |
current = current.next; | |
carry = sum / 10; | |
} | |
if (carry > 0) current.next = new ListNode(carry); | |
return sentinel.next; | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment