首页 > 其他 > 详细

【Add Two Numbers】

时间:2015-04-28 22:46:20      阅读:340      评论: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

代码

/**
 * 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 dummy(-1);
        ListNode *p = &dummy,*p1 = l1,*p2 = l2;
        int carry = 0;
        while(p1!=NULL || p2!=NULL){
            const int v1 = p1==NULL?0:p1->val, v2 = p2==NULL?0:p2->val, v = (v1+v2+carry)%10;
            carry = (v1+v2+carry)/10;
            p->next = new ListNode(v);
            p = p->next;
            p1 = p1==NULL ? NULL : p1->next;
            p2 = p2==NULL ? NULL : p2->next;
        }
        if ( carry > 0 ) p->next = new ListNode(carry);
        return dummy.next;
    }
};

Tips

核心在于判断while停止条件:直到l1和l2都走完了才退出;如果l1或者l2先走完了,就当该位是0。

上面这种思路的好处是可以简化代码。

【Add Two Numbers】

原文:http://www.cnblogs.com/xbf9xbf/p/4464184.html

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