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

leetcode -day20 Add Two Numbers

时间:2014-05-21 10:49:10      阅读:221      评论:0      收藏:0      [点我收藏+]

标签:leetcode   oj   算法   

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

标签:leetcode   oj   算法   

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

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