LeetCode 2. Add Two Numbers

https://leetcode.com/problems/add-two-numbers/

模拟高精度加法,传进来的是链表,可以稍微优化一下。

/**
 * 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* pos=NULL,*head=NULL,*m;
        int cnt=0;
        while(l1||l2)
        {
            m= new ListNode(0);
            if(l1&&l2)
                m->val=l1->val+l2->val,l1=l1->next,l2=l2->next;
            else if(l1)
            {
                if(!cnt)
                {
                    pos->next=l1;
                    goto li;
                }
                else
                    m->val=l1->val,l1=l1->next;
            }
            else
            {
                if(!cnt)
                {
                    pos->next=l2;
                    goto li;
                }
                else
                    m->val=l2->val,l2=l2->next;
            }
            m->val+=cnt;
            if(m->val>=10)
                m->val-=10,cnt=1;
            else
                cnt=0;
            if(!head)
                pos=head=m;
            else
                pos->next=m,pos=m;
        }
        if(cnt)
        {
            m= new ListNode(1);
            pos->next=m;
        }
        li:;
        return head;
    }
    
};

 

posted @ 2016-12-04 21:37  Luke_Ye  阅读(120)  评论(0编辑  收藏  举报