Add Two Numbers
Description
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.
Tags: Linked List, Math
思路
题意我也是看了好久才看懂,就是以链表表示一个数,低位在前,高位在后,所以题中的例子就是 342 + 465 = 807
,所以我们模拟计算即可。
/**
* 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 node = new ListNode(0);
ListNode n1 = l1, n2 = l2, t = node;
int sum = 0;
while (n1 != null || n2 != null) {
sum /= 10;
if (n1 != null) {
sum += n1.val;
n1 = n1.next;
}
if (n2 != null) {
sum += n2.val;
n2 = n2.next;
}
t.next = new ListNode(sum % 10);
t = t.next;
}
if (sum / 10 != 0) t.next = new ListNode(1);
return node.next;
}
}
class Solution {
fun addTwoNumbers(l1: ListNode?, l2: ListNode?): ListNode? {
var n1 = l1
var n2 = l2
var firstNode: ListNode? = null
var prev: ListNode? = null
var co = 0
while (n1 != null || n2 != null) {
val van1 = n1?.`val` ?: 0
val van2 = n2?.`val` ?: 0
var item = van1 + van2 + co
if (item >= 10) {
item %= 10
co = 1
} else {
co = 0
}
if (firstNode == null) {
firstNode = ListNode(item)
prev = firstNode
} else {
val newNode = ListNode(item)
prev!!.next = newNode
prev = newNode
}
n1 = n1?.next
n2 = n2?.next
}
if (co == 1) {
prev!!.next = ListNode(1)
}
return firstNode
}
}
结语
如果你同我们一样热爱数据结构、算法、LeetCode,可以关注我们 GitHub 上的 LeetCode 题解:LeetCode-Solution