C++两数相加(完整可运行代码)

题目描述:

给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。

如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。

您可以假设除了数字 0 之外,这两个数都不会以 0 开头。

示例:

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

输出:7 -> 0 -> 8

原因:342 + 465 = 807

先分析下题目,意思是两个非负的整数他们是用链表的形式来表示的,而且各自的位数是逆序。也就是说比如342这个数字,正常链表顺序是 (3 -> 4 -> 2),而逆序则为(2 -> 4 -> 3)。

现在的需求是需要一个新的链表来表示它们的和。

根据四则运算法则,一般都是从个位数开始相加,因为这里是逆序,所以从头结点出发,第一个结点就是个位数。

完整版代码:

#include <iostream>
#include <sstream>
#include <string>

using namespace std;

struct ListNode {
    int val;
    ListNode *next;
    ListNode() : val(0), next(nullptr) {}
    ListNode(int x) : val(x), next(nullptr) {}
};


//string reverse(string str){
//	if(str.length()==1) return str;
//	return str[str.length()-1]+reverse(str.substr(0,str.length()-1)); 
//}

ListNode* createListNode(string num){
	int len = num.length();
	if(len>0){
		ListNode* head = new ListNode(num[0]-'0');
		ListNode* front = head;
		ListNode * tmp = NULL;
		for(int i=1;i<len;i++){
			tmp = new ListNode(num[i]-'0');
			front->next = tmp;
			front = tmp;
		}
		return head;
	}	
	return NULL;
}

string strAdd(string a,string b){
	string result="";
	int len = min(a.length(),b.length());
	int jinwei = 0;
	int i;
	for(i=0;i<len;i++){
		int temp = (a[i]-'0')+(b[i]-'0')+jinwei;
		result.push_back('0'+(temp%10));
		jinwei = temp/10;
	}
	while(i<a.length()){
		int temp = (a[i]-'0')+jinwei;
		result.push_back('0'+(temp%10));
		jinwei = temp/10;
		i++;
	}
	while(i<b.length()){
		int temp = ('0'+b[i])+jinwei;
		result.push_back('0'+(temp%10));
		jinwei = temp/10;
		i++;
	}
	if(jinwei!=0){
		result.push_back('0'+(jinwei));
	}
	return result;
} 
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
    stringstream ss;
    string s1 = "",s2 = "";
    while(l1!=NULL){
        s1.push_back('0'+(l1->val));
        l1 = l1->next;
    }
    while(l2!=NULL){
        s2.push_back('0'+(l2->val));
        l2 = l2->next;
    }
	string result = strAdd(s1,s2);     
    return createListNode(result);
}

int main(){
	ListNode* l1 = createListNode("243");
 	ListNode* l2 = createListNode("564");
	ListNode* result = addTwoNumbers(l1,l2);
	while(result!=NULL){
		cout<<result->val;
		result = result->next;
	}
	return 1;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值