每日一題3:兩數相加

leetcode刷題筆記新地址(仍在更新)

https://github.com/MyLinChi/LeetcodeNote

問題描述

給出兩個 非空 的鏈表用來表示兩個非負的整數。其中,它們各自的位數是按照 逆序 的方式存儲的,並且它們的每個節點只能存儲 一位 數字。

如果,我們將這兩個數相加起來,則會返回一個新的鏈表來表示它們的和。

您可以假設除了數字 0 之外,這兩個數都不會以 0 開頭。

示例:

輸入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
輸出:7 -> 0 -> 8
原因:342 + 465 = 807

問題分析

在計算機中實現兩個數相加的方法是
S=A+B+CS = A + B + C
S-和,A-被加數,B-被加數,C-進位
注意事項
1.初始時 C=0C=0
2.當其中一個鏈表的數加完時,計算的式子將變成S=A+CS = A + C(或S=B+CS = B + C)的形式,因此要對剩餘的鏈表中的數據繼續相加。
3.當所有的鏈表中的元素已經計算完畢,如果C!=0C!=0,那麼應該給結果鏈表多分配一個結點存儲進位。
4.鏈表的輸入採用頭插法,根據計算過程和結果的形式,結果鏈表的生成採用尾插法;爲了便於鏈表的操作,開始時給結果鏈表分配一個空結點,只需返回空結點指向的鏈表即可。

代碼

#include<iostream>
#include<string>
using namespace std;

/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/

struct ListNode {
	int val;
	ListNode *next;
	ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
	int c;
	Solution() :c(0){}
	ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
		ListNode * ans = new ListNode(0);//null node
		ListNode * tail = ans;
		while (l1&&l2)
		{
			int sum = l1->val + l2->val + c;
			c = sum / 10;
			tail->next = new ListNode(sum % 10);
			tail = tail->next;
			l1 = l1->next;
			l2 = l2->next;
		}
		if (l1){
			while (l1)
			{
				int sum = l1->val + c;
				c = sum / 10;
				tail->next = new ListNode(sum % 10);
				tail = tail->next;
				l1 = l1->next;
			}
		}else if (l2){
			while (l2)
			{
				int sum = l2->val + c;
				c = sum / 10;
				tail->next = new ListNode(sum % 10);
				tail = tail->next;
				l2 = l2->next;
			}
		}
		if (c){
			tail->next = new ListNode(c);
			tail = tail->next;
		}
		return ans->next;
	}
};

int main()
{
	ListNode * a = NULL, *b = NULL,*tp = NULL;
	char t;
	while (cin >> t){
		if ('#' == t)break;
		tp = a;
		a = new ListNode(t - '0');
		a->next = tp;
	}

	while (cin >> t){
		if ('#' == t)break;
		tp = b;
		b = new ListNode(t - '0');
		b->next = tp;
	}
	Solution s;
	ListNode * c;
	c = s.addTwoNumbers(a, b);
	return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章