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

2-Add Two Numbers

时间:2015-06-10 23:52:05      阅读:131      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!