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

leetcode 2 两数相加 考虑溢出

时间:2019-10-20 00:56:20      阅读:76      评论:0      收藏:0      [点我收藏+]

标签:pre   init   直接   null   ber   while   color   code   ext   

先用int存了结果然后出错,int溢出了。

真是憨批嗷。

不用考虑保存结果,直接一位一位计算就行。

感觉被描述误导了。

/**
 * 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* head=new ListNode(0);
        ListNode* tp=head;
        int sum=0;
        bool carry=false;//最多进一位
         while(l1!=NULL||l2!=NULL)
        {
            sum=0;
            if(l1!=NULL)
            {
                sum+=l1->val;
                l1=l1->next;
            }
            if(l2!=NULL)
            {
                sum+=l2->val;
                l2=l2->next;
            }
            if(carry)
                sum++;
            tp->next=new ListNode(sum%10);
            tp=tp->next;
            carry=sum>=10?true:false;
        }
        if(carry)
        {
            tp->next=new ListNode(1);
        }
        
        return head->next;
    }
};

 

leetcode 2 两数相加 考虑溢出

标签:pre   init   直接   null   ber   while   color   code   ext   

原文地址:https://www.cnblogs.com/lqerio/p/11706445.html

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