AddTwoNumbers
描述
10多年的台州网站建设经验,针对设计、前端、开发、售后、文案、推广等六对一服务,响应快,48小时及时工作处理。全网整合营销推广的优势是能够根据用户设备显示端的尺寸不同,自动调整台州建站的显示方式,使网站能够适用不同显示终端,在浏览器中调整网站的宽度,无论在任何一种浏览器上浏览网站,都能展现优雅布局与设计,从而大程度地提升浏览体验。成都创新互联公司从事“台州网站设计”,“台州网站推广”以来,每个客户项目都认真落实执行。
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; } };
《完》
分享名称:AddTwoNumbers
文章起源:http://azwzsj.com/article/ihjesj.html