时间: 2019-10-09 11:19 PM
题目地址: https://leetcode.com/problems/add-two-numbers/
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.
给定两个非空链表,它们代表两个非负整数。 这些数字以相反的顺序存储,并且它们的每个节点都包含一个数字。 将两个数字相加,并将其作为链表返回。
假设除0以外,数字的第一位非0。
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
Solution:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode result = null;
ListNode pointer = null;
int carry = 0;
int index = 0;
do {
int count = 0;
int val1 = 0;
int val2 = 0;
if (null == l1) {
count++;
} else {
val1 = l1.val;
l1 = l1.next;
}
if (null == l2) {
count++;
} else {
val2 = l2.val;
l2 = l2.next;
}
if (count == 2 && carry == 0) {
break;
}
int val = val1 + val2 + carry;
if (val >= 10) {
carry = 1;
val -= 10;
} else {
carry = 0;
}
ListNode tmp = new ListNode(val);
if (0 == index++) {
result = tmp;
pointer = tmp;
} else {
pointer.next = tmp;
pointer = tmp;
}
} while (true);
return result;
}
}
Runtime: 2 ms, faster than 79.13% of Java online submissions for Add Two Numbers.
Memory Usage: 45 MB, less than 84.32% of Java online submissions for Add Two Numbers.