Add Two Numbers
2019-08-16 07:49:05来源:博客园 阅读 ()
Add Two Numbers
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.
Code
//
// main.cpp
// 两个数字的加法操作
//
// Created by mac on 2019/7/14.
// Copyright ? 2019 mac. All rights reserved.
//
#include <iostream>
#include <vector>
#include <list>
#include <algorithm>
using namespace std;
//Definition for singly-linked list.
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
//NULL是不是0? 是0
class Solution {
public:
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
ListNode preHead(0), *p = &preHead;
int extra = 0;
//如果l1=nullptr 且l2=nullptr 且extra=0 那么这个循环就结束了
while (l1 || l2 || extra) {
if (l1) extra += l1->val, l1 = l1->next;
if (l2) extra += l2->val, l2 = l2->next;
p->next = new ListNode(extra % 10);
extra /= 10;
p = p->next;
}
return preHead.next;
}
};
int main(int argc, const char * argv[]) {
// insert code here...
Solution So;
ListNode *l1=nullptr;
//这个地方的逻辑判断不仅仅限于数字的运算
//if语句不会被执行
if (l1||0) {
cout<<"执行这句话咯,嘿嘿.."<<endl;
}
ListNode *l2=nullptr;
for (int i=1; i<4; i++) {
ListNode *p=new ListNode(i);
p->next=l1;
l1=p;
ListNode *q=new ListNode(i+1);
q->next=l2;
l2=q;
}
ListNode*l3 = So.addTwoNumbers(l1, l2);
while (l3!=NULL) {
cout<<l3->val<<endl;
l3=l3->next;
}
cout<<"+++++++++++++++++++++++"<<endl;
cout<<NULL<<endl;//NULL是0
return 0;
}
运行结果
7
5
3
+++++++++++++++++++++++
0
Program ended with exit code: 0
参考文献
- https://leetcode.com/problems/add-two-numbers/
原文链接:https://www.cnblogs.com/overlows/p/11192307.html
如有疑问请与原作者联系
标签:
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有
- CodeForces 710D Two Arithmetic Progressions 2020-03-06
- Median of Two Sorted Arrays 2019-08-16
- Two Sum 2019-08-16
- GetPixelAddress()函数Alpha通道会丢失 2019-01-23
- poj-2236 wireless network(并查集) 2018-12-04
IDC资讯: 主机资讯 注册资讯 托管资讯 vps资讯 网站建设
网站运营: 建站经验 策划盈利 搜索优化 网站推广 免费资源
网络编程: Asp.Net编程 Asp编程 Php编程 Xml编程 Access Mssql Mysql 其它
服务器技术: Web服务器 Ftp服务器 Mail服务器 Dns服务器 安全防护
软件技巧: 其它软件 Word Excel Powerpoint Ghost Vista QQ空间 QQ FlashGet 迅雷
网页制作: FrontPages Dreamweaver Javascript css photoshop fireworks Flash