1. 程式人生 > >領釦兩數相加

領釦兩數相加

趕腳解法依然暴力,不過好在用時還不算特別多。

class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
       	ListNode *result = new ListNode(0);
		ListNode *head = result;
		int carry = 0;//記錄是否需要進位
		while (l1 != NULL || l2 != NULL)
		{
			if (l1 != NULL && l2 != NULL)
			{
				result->val = l1->val + l2->val;
				l1 = l1->next;
				l2 = l2->next;
			}
			else if (l1 == NULL && l2 != NULL)
			{
				result->val = l2->val;
				l2 = l2->next;
			}
			else
			{
				result->val = l1->val;
				l1 = l1->next;
			}
			if (carry == 1)
			{
				result->val++;
				carry = 0;
			}		
			if (result->val > 9)
			{
				result->val = result->val - 10;
				carry = 1;
			}
            if (l1 == NULL && l2 == NULL&&carry == 0)
				break;
			ListNode *p = new ListNode(0);
			result->next = p;
			result = result->next;
		}
		if(result->val==0&&carry==1)
            result->val=1;
		return head;
	}
};