首页 > 其他 > 详细

leetcode--Add Two Numbers

时间:2014-02-28 06:26:45      阅读:515      评论: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

 

Have you been asked this question in an interview? 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode result = new ListNode(0);
        ListNode nextNode = result;
        if(l1 == null)
            result.next = l2;
        if(l2 == null)
            result.next = l1;
        int carry = 0;
        while(l1 != null && l2 != null){
            int sum = l1.val + l2.val + carry;
            nextNode.next = new ListNode(sum % 10);
            carry = sum / 10;
            nextNode = nextNode.next;
            l1 = l1.next;
            l2 = l2.next;
        }
     
        nextNode.next = (l1 == null) ? l2 : l1;
        while(nextNode.next != null){
            nextNode = nextNode.next;
            int sum = nextNode.val + carry;
            nextNode.val = sum % 10;
            carry = sum / 10;
        }
        if(carry != 0){
            nextNode.next = new ListNode(carry);
            nextNode = nextNode.next;
        }
        nextNode.next = null;
        result = result.next;
        return result;
    }
}

  

leetcode--Add Two Numbers,布布扣,bubuko.com

leetcode--Add Two Numbers

原文:http://www.cnblogs.com/averillzheng/p/3571162.html

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