Interview - Add two number - #2

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Interview - Add two number - #2相关的知识,希望对你有一定的参考价值。

You are given two linked lists representing two non-negative numbers. 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.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

题目比较简单, 主要考察链表操作的熟练程度, 以及各种边界情况的处理, 这种题目, 要一次写对, 不留 bug.

 1 public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
 2         if (l1 == null) return l2;
 3         if (l2 == null) return l1;
 4         
 5         ListNode head = new ListNode(0);
 6         ListNode curr = head;
 7         boolean isCarry = false;
 8         while (l1 != null || l2 != null) {
 9             int val = (isCarry ? 1 : 0) + (l1 == null ? 0 : l1.val) + (l2 == null ? 0 : l2.val);
10             if (val >= 10) {
11                 isCarry = true;
12                 val -= 10;
13             } else {
14                 isCarry = false;
15             }
16             ListNode node = new ListNode(val);
17             curr.next = node;
18             curr = node;
19             l1 = l1 == null ? null : l1.next;
20             l2 = l2 == null ? null : l2.next;
21         }
22         
23         if (isCarry) {
24             ListNode node = new ListNode(1);
25             curr.next = node;
26         }
27         
28         return head.next;
29     }

 

以上是关于Interview - Add two number - #2的主要内容,如果未能解决你的问题,请参考以下文章

leetcode mock interview-two sum II

Coursera Algorithms week2 基础排序 Interview Questions: 1 Intersection of two sets

Coursera Algorithms week2 栈和队列 Interview Questions: Queue with two stacks

LC.02. Add Two Numbers

Leetcode 2. Add Two Numbers

Leetcode 2. Add Two Numbers