首页 > 其他 > 详细

2-Add Two Numbers

时间:2015-06-10 23:50:35      阅读:311      评论: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

 

注意一下有些特殊的测试用例:Input: [1], [9,9]       Input: [1,8], [0]        Input: [5], [5]        Input:   [0], [0]

技术分享
 1 public class Solution {
 2 
 3 public ListNode addTwoNumbers(ListNode x, ListNode y) {
 4         int temp = 0;
 5         int pre = 0;
 6         int carry = 0;
 7         ListNode top = new ListNode(0);
 8         ListNode sum = top;
 9         while (x != null || y != null || carry != 0) {
10             if (x != null) {
11                 temp += x.val;
12                 x = x.next;
13             }
14             if (y != null) {
15                 temp += y.val;
16                 y = y.next;
17             }
18 
19             temp += carry;
20 
21             if (temp >= 10) {
22                 carry = 1;
23                 pre = temp % 10;
24                 temp = 0;
25             } else {
26                 carry = 0;
27                 pre = temp;
28                 temp = 0;
29             }
30             sum.val = pre;
31             if (carry != 0 || x != null || y != null) {
32                 sum.next = new ListNode(0);
33                 sum = sum.next;
34             }
35         }
36         return top;
37     }
38 }
View Code

注意一下进位,边界。跑了412 ms

2-Add Two Numbers

原文:http://www.cnblogs.com/AloneAli/p/4567705.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!