2. Add Two Numbers

    xiaoxiao2021-03-25  67

    简单相加,对sum的求法分类讨论

    /** * 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* temp1=l1; ListNode* temp2=l2; ListNode* result=NULL; ListNode* now=NULL; int carry=0; while(1) { int sum; if(temp1!=NULL&&temp2!=NULL) sum=temp1->val+temp2->val+carry; else if(temp1==NULL&&temp2!=NULL) sum=temp2->val+carry; else if(temp1!=NULL&&temp2==NULL) sum=temp1->val+carry; else if(carry!=0) sum=carry; else break; carry=sum/10; if(result==NULL) { result=new ListNode(sum%10); now=result; } else { now->next=new ListNode(sum%10); now=now->next; } if(temp1!=NULL) temp1=temp1->next; if(temp2!=NULL) temp2=temp2->next; } return result; } };
    转载请注明原文地址: https://ju.6miu.com/read-40349.html

    最新回复(0)