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

LeetCode|Add Two Numbers

时间:2016-06-20 15:31:56      阅读:119      评论: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

 

我的第一种解法 就是建立一个ListNode,保存每位数相加的和,别忘记用一个变量来存储进位。 将每次计算得到的数字用ListNode连接在一次,保存返回就可以了。

class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode* i=l1;
        ListNode* j=l2;
        ListNode* ans=NULL;
        int c=0;
        while(i!=NULL&&j!=NULL)
        {
            int x=i->val+j->val+c;
            ListNode* node=new ListNode(x%10);
            c=x/10;
            addNode(node,ans);
            i=i->next;
            j=j->next;
        }
        while(i!=NULL)
        {
            int x=i->val+c;
            ListNode* node=new ListNode(x%10);
            c=x/10;
            addNode(node,ans);
            i=i->next;
        }
        while(j!=NULL)
        {
            int x=j->val+c;
            ListNode* node=new ListNode(x%10);
            c=x/10;
            addNode(node,ans);
            j=j->next;
        }
        while(c!=0)
        {
            int x=c;
            ListNode* node=new ListNode(x%10);
            c=x/10;
            addNode(node,ans);
        }
        return ans;
    }
    
    void addNode(ListNode* node, ListNode* &t)
    {
        if(t==NULL)
        {
            t=node;
            return;
        }
        ListNode* ss=t;
        while(ss->next!=NULL)
        {
            ss=ss->next;
        }
        ss->next=node;
    }
    
};

问题是,运算出来的结果只打败了5%的代码,看来这里还存在很大优化的空间。

LeetCode|Add Two Numbers

标签:

原文地址:http://www.cnblogs.com/liluyu/p/5600416.html

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