AddTwoNumbers-创新互联
描述
二连浩特ssl适用于网站、小程序/APP、API接口等需要进行数据传输应用场景,ssl证书未来市场广阔!成为创新互联公司的ssl证书销售渠道,可以享受市场价格4-6折优惠!如果有意向欢迎电话联系或者加微信:18980820575(备注:SSL证书合作)期待与您的合作!You are given two linked lists representing two non-negative numbers. 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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
分析:342+465=807——>708
Add.h
#pragma once #includeusing namespace std; typedef struct ListNode{ int _var; ListNode *_next; ListNode(int var) :_var(var) , _next(NULL) {} }node, *node_p; class Solution { public: node_p add_two_number(ListNode *l1, ListNode *l2) { node_p NewHead = NULL; node_p pa = l1->_next; node_p pb = l2->_next; int mod = 0; while (pa != NULL || pb != NULL){ int a = 0; int b = 0; if (pa != NULL) a = pa->_var; if (pb != NULL) b = pb->_var; int ret = (a + b + mod) % 10; mod = (a + b + mod) / 10; node_p tmp = new node(ret); tmp->_next = NewHead; NewHead = tmp; if (pa != NULL) pa = pa->_next; if (pb != NULL) pb = pb->_next; } if (mod > 0){ node_p tmp = new node(mod); tmp->_next = NewHead; NewHead = tmp; } return NewHead; } };
Add.cpp
#include "Add_List.h" #includeusing namespace std; int main() { Solution s1; node_p l1 = new node(-1); node_p pa = l1; pa->_next = new node(4); pa = pa->_next; pa->_next = new node(6); pa = pa->_next; pa->_next = new node(7); pa = pa->_next; pa->_next = new node(8); node_p l2 = new node(-1); node_p pb = l2; pb->_next = new node(1); pb = pb->_next; pb->_next = new node(2); pb = pb->_next; pb->_next = new node(5); pb = pb->_next; pb->_next = new node(6); pb = pb->_next; pb->_next = new node(3); node_p ret=s1.add_two_number(l1,l2); system("pause"); return 0; }
调试查看结果:
// LeetCode, Add Two Numbers
// 时间复杂度 O(m+n),空间复杂度 O(1)
class Solution{ public: ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) { ListNode dummy(-1); // 头节点 int carry = 0; ListNode *prev = &dummy; for (ListNode *pa = l1, *pb = l2; pa != nullptr || pb != nullptr; pa = pa == nullptr ? nullptr : pa->next, pb = pb == nullptr ? nullptr : pb->next, prev = prev->next) { const int ai = pa == nullptr ? 0 : pa->val; const int bi = pb == nullptr ? 0 : pb->val; const int value = (ai + bi + carry) % 10; carry = (ai + bi + carry) / 10; prev->next = new ListNode(value); // 尾插法 } if (carry > 0) prev->next = new ListNode(carry); return dummy.next; } };
《完》
另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。
文章名称:AddTwoNumbers-创新互联
文章路径:http://azwzsj.com/article/cchgeo.html