天天看點

2.Add Two Numbers

Description:

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

  • Difficulty: Medium

簡單解釋一下題意,兩個位置颠倒(例如:892寫成298)的數字相加後,按正常順序輸出結果。

解題思路:

1.從左到右開始互加計算,倘若在某位相加和大于等于10,要向右一位加1,而不是左一位加1.

2.題目要求傳回的是連結清單,是以每進位得到的結果可以通過頭插法插入到連結清單首位,最後得到題目要求的正常順序的結果

ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {

          ListNode* head = new ListNode(0);

          ListNode* res = head;

          int tmp = 0;

          while(l1||l2||res){

             int num = (l1? l1->val:0) + (l2? l2->val:0) + tmp;

             tmp = num / 10;

             res->next = new ListNode(num % 10);

             res = res->next;

             if(l1) l1 = l1->next;

             if(l2) l2 = l2->next;

          }

          return head->next;

}