My Solution: Using `l1+l2` and `l2+l1` to make an alignment!


  • 0

    Using l1+l2 and l2+l1 to make an alignment, we can get the sum of each unit with help of two bool f1 and f2 witch indicate each of the val is available or not. Then we store the res in a vector to get the carries and build the LinkedList res.

    class Solution 
    {
    public:
        ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) 
        {
        	bool f1 = false;
        	bool f2 = false;
        	vector<int> sum;
            ListNode *res = new ListNode(0);
            ListNode *p = l1;
            ListNode *q = l2;
            while(p && q)
            {
            	if(f1 || f2)
            	{
            		int temp = (f1 ? p->val : 0) + (f2 ? q->val : 0);
            		sum.push_back(temp);
            	}
            	p = p->next;
            	q = q->next;
            	if(f1 && f2 && p == q)
            		break;
            	if(p == NULL)
            	{
            		p = l2;
            		f1 = true;
            	}
            	if(q == NULL)
            	{
            		q = l1;
            		f2 = true;
            	}
            }
    
            int carry = 0;
            for(int i = sum.size()-1; i >= 0; --i)
            {
            	sum[i] = sum[i] + carry;
            	carry = sum[i] / 10;
            	sum[i] %= 10;
            }
            if(carry)
            	sum.insert(sum.begin(), carry);
    
            ListNode *cur = res;
            for(int i = 0; i < sum.size(); ++i)
            {
            	cur->next = new ListNode(sum[i]);
            	cur = cur->next;
            }
            return res->next;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.