2 - Add Two Numbers
程序员文章站
2024-03-17 21:56:34
...
Problem
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.
Code
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode ret = new ListNode(0);
ListNode t = ret;
int p = 0;
while (l1 != null && l2 != null) {
int tmp = p + l1.val + l2.val;
t.next = new ListNode(tmp % 10);
p = tmp / 10;
l1 = l1.next;
l2 = l2.next;
t = t.next;
}
while (l1 != null) {
int tmp = p + l1.val;
t.next = new ListNode(tmp % 10);
p = tmp / 10;
l1 = l1.next;
t = t.next;
}
while (l2 != null) {
int tmp = p + l2.val;
t.next = new ListNode(tmp % 10);
p = tmp / 10;
l2 = l2.next;
t = t.next;
}
if (p != 0) {
t.next = new ListNode(p);
}
return ret.next == null ? ret : ret.next;
}
}
推荐阅读