Problem:
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
Solution:
Main Idea: Add each bit one by one, note that carry in and carry out should be taken into consideration.
Note that when finishing the traversal, if carryIn is not zero, need to append carryIn at the end.
Code: 又一次AC啦 吊吊吊
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int carryIn = 0;
ListNode newHead = new ListNode(0);
ListNode current = newHead;
while (l1 != null && l2 != null) {
ListNode node = new ListNode((l1.val + l2.val + carryIn) % 10);
carryIn = (l1.val + l2.val + carryIn) / 10;
l1 = l1.next;
l2 = l2.next;
current.next = node;
current = current.next;
}
if (l1 != null || l2 != null) {
while (l1 != null) {
ListNode node = new ListNode((l1.val + carryIn) % 10);
carryIn = (l1.val + carryIn) / 10;
l1 = l1.next;
current.next = node;
current = current.next;
}
while (l2 != null) {
ListNode node = new ListNode((l2.val + carryIn) % 10);
carryIn = (l2.val + carryIn) / 10;
l2 = l2.next;
current.next = node;
current = current.next;
}
}
if (carryIn == 1) {
current.next = new ListNode(1);
}
return newHead.next;
}
}