標籤:

【LeetCode】#2——Add Two Numbers

QUESTION:

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)

Output: 7 -> 0 -> 8

翻譯:

給出兩個非空鏈表,表示兩個非負整數。數字以相反的順序存儲,每個節點包含一個位數。添加兩個數字並將其返回為鏈表。

你可以假設這兩個數字不包含任何前導零,除了數字0本身。

輸入: (2 -> 4 -> 3) + (5 -> 6 -> 4)

輸出: 7 -> 0 -> 8

解決:

1.進位向後;

2.鏈表l1或l2為空時,直接返回;

3.鏈表l1和l2長度可能不同,因此要注意處理某個鏈表剩餘的高位;

/*** 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) {if (l1 == NULL) return l2;if (l2 == NULL) return l1;ListNode *head = new ListNode(0);//head保存指針ListNode *p = head;int carry = 0;while(l1 != NULL && l2!=NULL){int sum = carry + l1->val + l2->val;p->next= new ListNode(sum % 10);carry = sum / 10;l1 = l1->next;l2 = l2->next;p = p->next;}while(l1 != NULL) {int sum = carry + l1->val;p->next= new ListNode(sum % 10);carry = sum /10;l1 = l1->next;p= p->next;}while(l2 != NULL) {int sum = carry + l2->val;p->next= new ListNode(sum % 10);carry = sum /10;l2 = l2->next;p = p->next;}if (carry != 0) {p->next= new ListNode(carry);}return head->next;}};

推薦閱讀:

LeetCode的一個bug?
雙端隊列
leetcode-1
029 Divide Two Integers[M]

TAG:LeetCode |