leetcode 2 两数相加 考虑溢出

先用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;
    }
};

猜你喜欢

转载自www.cnblogs.com/lqerio/p/11706445.html