Skip to content

Instantly share code, notes, and snippets.

@InterviewBytes
Created June 6, 2017 21:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save InterviewBytes/1a7e71c0377201d04f2de450601e6294 to your computer and use it in GitHub Desktop.
Save InterviewBytes/1a7e71c0377201d04f2de450601e6294 to your computer and use it in GitHub Desktop.
LinkedLists - Add two numbers
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