首页 > 其他 > 详细

【leetcode】2. Add Two Numbers

时间:2015-07-15 17:09:16      阅读:200      评论:0      收藏:0      [点我收藏+]
@requires_authorization
@author johnsondu
@create_time 2015.7.15 14:54
@url [add two numbers](https://leetcode.com/problems/add-two-numbers/)
/**
 *    链表模拟大数相加
 *    时间复杂度: O(n)
 *    空间复杂度: O(n)
 */
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode *head = new ListNode(0);
        ListNode *cur = head;

        int carry = 0;
        while(l1 || l2 || carry){
            int tmp = carry;
            if(l1 != NULL) {
                tmp = tmp + l1->val;
                l1 = l1->next;
            }
            if(l2 != NULL) {
                tmp = tmp + l2->val;
                l2 = l2->next;
            }
            carry = tmp / 10;
            ListNode *node = new ListNode(tmp % 10);
            cur->next = node;
            cur = cur->next;
        }
        return head->next;
    }
};

版权声明:本文为博主原创文章,未经博主允许不得转载。

【leetcode】2. Add Two Numbers

原文:http://blog.csdn.net/zone_programming/article/details/46893543

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