码迷,mamicode.com
首页 > 其他好文 > 详细

Interview - Add two number - #2

时间:2016-01-29 19:39:15      阅读:133      评论:0      收藏:0      [点我收藏+]

标签:

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

标签:

原文地址:http://www.cnblogs.com/dbalgorithm/p/5169232.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!