首页 > 其他 > 详细

leetcode -day20 Add Two Numbers

时间:2014-05-21 10:48:31      阅读:356      评论:0      收藏:0      [点我收藏+]
1、


Add Two Numbers 

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

分析:开始没看懂题意,这中间加法涉及到进位问题,进的位在下一个数体现。而且看题目以为数字以相反的顺序存放,开始写还用了翻转链表,后来测试用例中有问题才发现不需要翻转链表。注意输入链表不一定等长,设置一个进位标志。

如下:

class Solution {
public:
    ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
        if(!l1){
            return l2;
        }else if(!l2){
            return l1;
        }
        ListNode* head = NULL;
        ListNode* node1 = l1;
        ListNode* node2 = l2;
        ListNode* preNode = NULL;
        int takeOver = 0;
        int val = 0;
        while(node1 || node2){
            if(node1 && node2){
                val = node1->val + node2->val+takeOver;
                node1 = node1->next;
                node2 = node2->next;
            }else if(node1){
                val = node1->val + takeOver;
                node1 = node1->next;
            }else if(node2){
                val = node2->val + takeOver;
                node2 = node2->next;
            }
            takeOver = val/10;
            val %= 10;
            ListNode* tempNode = new ListNode(val);
            if(!preNode){
                head = tempNode;
            }else{
                preNode->next = tempNode;
            }
            preNode = tempNode;
            
        }
        if(takeOver){
            ListNode* tempNode = new ListNode(1);
            preNode->next = tempNode;
        }
        return head;
        
    }
};


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

leetcode -day20 Add Two Numbers

原文:http://blog.csdn.net/kuaile123/article/details/26401399

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