码迷,mamicode.com
首页 > 编程语言 > 详细

[LeetCode] 002. Add Two Numbers (Medium) (C++/Java/Python)

时间:2015-02-27 13:37:39      阅读:193      评论:0      收藏:0      [点我收藏+]

标签:c++   leetcode   python   java   

索引:[LeetCode] Leetcode 题解索引 (C++/Java/Python/Sql)
Github: https://github.com/illuz/leetcode


002.Add_Two_Numbers (Medium)

链接

题目:https://oj.leetcode.com/problems/add-two-numbers/
代码(github):https://github.com/illuz/leetcode

题意

求两个 List 相加产生的新的一个 List。

分析

直接模拟就可以了。

代码

C++:

class Solution {
public:
    ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
        ListNode *ret = new ListNode(0);
        ListNode *cur = ret;
        int sum = 0;
        while (1) {
            if (l1 != NULL) {
                sum += l1->val;
                l1 = l1->next;
            }
            if (l2 != NULL) {
                sum += l2->val;
                l2 = l2->next;
            }
            cur->val = sum % 10;
            sum /= 10;
            if (l1 != NULL || l2 != NULL || sum)
                cur = (cur->next = new ListNode(0));
            else
                break;
        }
        return ret;
    }
};


Java:

public class Solution {

    // Definition for singly-linked list.
    public static class ListNode {
        int val;
        ListNode next;
        ListNode(int x) {
            val = x;
            next = null;
        }
    }

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode ret = new ListNode(0);
        ListNode cur = ret;

        int sum = 0;
        while (true) {
            if (l1 != null) {
                sum += l1.val;
                l1 = l1.next;
            }
            if (l2 != null) {
                sum += l2.val;
                l2 = l2.next;
            }
            cur.val = sum % 10;
            sum /= 10;
            if (l1 != null || l2 != null || sum != 0) {
                cur = (cur.next = new ListNode(0));
            } else {
                break;
            }
        }
        return ret;
    }
}


Python:

class Solution:
    # @return a ListNode
    def addTwoNumbers(self, l1, l2):
        ret = ListNode(0)
        cur = ret

        sum = 0
        while True:
            if l1 != None:
                sum += l1.val
                l1 = l1.next
            if l2 != None:
                sum += l2.val
                l2 = l2.next

            cur.val = sum % 10
            sum /= 10
            if l1 != None or l2 != None or sum != 0:
                cur.next = ListNode(0)
                cur = cur.next
            else:
                break

        return ret



[LeetCode] 002. Add Two Numbers (Medium) (C++/Java/Python)

标签:c++   leetcode   python   java   

原文地址:http://blog.csdn.net/hcbbt/article/details/43966461

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