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

[leetcode] 2. Add Two Numbers

时间:2014-06-17 23:38:04      阅读:341      评论:0      收藏:0      [点我收藏+]

标签:des   style   class   blog   code   ext   

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

Solution: link list

简单,注意两点:

1. 加到最后,可能还有进位

2. 链表实现时,可以多申请一个node的空间为x,返回x.next,可使代码更简洁。

#include <iostream>
#include <vector>

//  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 out = ListNode(0);
        ListNode *tail = &out;

        if(!l1 || !l2)
        {
            return NULL;
        }

        int carry = 0;
        while(l1 && l2)
        {
            int s = carry + l1->val + l2->val;
            carry = s / 10;
            s = s % 10;
            l1 = l1->next;
            l2 = l2->next;

            ListNode *temp = new ListNode(s);
            tail->next = temp;
            tail = tail->next;
        }

        if(l2)
        {
            l1 = l2;
        }

        while(l1)
        {
            int s = l1->val + carry;
            carry = s / 10;
            s = s % 10;
            l1 = l1->next;

            ListNode *temp = new ListNode(s);
            tail->next = temp;
            tail = tail->next;
        }

        if(carry)
        {
            ListNode *temp = new ListNode(carry);
            tail->next = temp;
            tail = tail->next;
        }

        return out.next;
    }
};

 

[leetcode] 2. Add Two Numbers,布布扣,bubuko.com

[leetcode] 2. Add Two Numbers

标签:des   style   class   blog   code   ext   

原文地址:http://www.cnblogs.com/xjsxjtu/p/3793600.html

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