题目描述
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.
Example
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
对两个链表求和,链表的低位对应数字的低位。
解题思路
用一个 carry 存储进位,一直加到 l1,l2 为 null,且 carry 为 0 时,运算完成。
代码
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
if (l1 == null || l2 == null)
return null;
ListNode first = new ListNode(-1);
ListNode node = first;
int carry = 0;
while (l1 != null || l2 != null || carry != 0) {
int a = 0;
int b = 0;
if (l1 != null) {
a = l1.val;
l1 = l1.next;
}
if (l2 != null) {
b = l2.val;
l2 = l2.next;
}
node.next = new ListNode((a+b+carry)%10);
node = node.next;
carry = (a+b+carry) / 10;
}
return first.next;
}
}
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于