Leetcode刷題:2. Add Two Numbers

題目:

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.

Example

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.


思路:

STL 有一個專門的結構體叫做 div_t, 其包含兩個成員,分別是 quot(quotient) 與 rem(remainder). 用來做什麼,從命名上是否可以看出一點端倪呢?

舉例說明.

 38 / 5 == 7 remainder 3

用 C++ 來描述,便是:

 div_t result = div(38, 5);
 cout << result.quot << result.rem;

前者爲被除後的結果,後者爲餘數。


代碼:

#include <cstddef>
#include <cstdlib>

// 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 dummy(0);
		// 創建輸出鏈表指針變量
		ListNode *tail = &dummy;

		// 初始化div_t變量
		div_t sum = { 0, 0 };

		for (div_t sum = { 0, 0 }; sum.quot || l1 || l2; tail = tail->next)
		{
			// 如果l1鏈表當前位置有數值
			if (l1){
				sum.quot += l1->val;
				l1 = l1->next;
			}

			// 如果l2鏈表當前位置有數值
			if (l2){
				sum.quot += l2->val;
				l2 = l2->next;
			}

			// 計算進位值
			sum = div(sum.quot, 10);

			//tail->val = sum.rem;
			// 創建ListNode對象存儲個位值
			tail->next = new ListNode(sum.rem);
		}

		return dummy.next;
	}
};


發佈了33 篇原創文章 · 獲贊 19 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章