LeetCode 2. Add Two Numbers
2018-03-30 本文已影响0人
DingZimin
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.
翻译:
给定两个非空链表,代表两个非负整数。数字倒序存储,每个节点包含一个数字。求这两个数字的和并作为一个链表返回。你可以假设这两个数字除了0本身外不包含前导0。
Solution:
这个问题很简单,只要同时遍历两个链表并对两个 Node 的值求和,直到下一个 Node 都是null
,一定要注意进位。
class Solution {
fun addTwoNumbers(l1: ListNode?, l2: ListNode?): ListNode? {
var node1 = l1
var node2 = l2
val result = ListNode(0)
var current = result
var c = 0
while (true) {
val sum = (node1?.`val` ?: 0) + (node2?.`val` ?: 0) + c
current.`val` = sum % 10
node1 = node1?.next
node2 = node2?.next
c = sum / 10
if (node1 != null || node2 != null || c != 0) {
current.next = ListNode(0)
current = current.next!!
} else {
break
}
}
return result
}
}