Add Two Numbers
程序员文章站
2022-05-29 10:26:36
"Add Two Numbers" Example: Code // // main.cpp // 两个数字的加法操作 // // Created by mac on 2019/7/14. // Copyright © 2019 mac. All rights reserved. // includ ......
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
参考文献
推荐阅读
-
MySQL的时间差函数(TIMESTAMPDIFF、DATEDIFF)、日期转换计算函数(date_add、day、date_format、str_to_date)
-
CMU-15445 LAB3:事务隔离,two-phase locking,锁管理器
-
dotnetcore-officeaddin-toolbox : Office 365 Add-in开发人员的工具箱
-
丑数(Ugly Numbers, UVa 136)
-
Python的“二维”字典 (two-dimension dictionary)定义与实现方法
-
Dockerfile 指令 ADD 和 COPY介绍
-
【转载】C#中ArrayList集合类使用Add方法添加元素
-
'Attempt to create two animations for cell' iOS
-
详解Dockerfile 中的 COPY 与 ADD 命令
-
ZOJ 1095. Humble Numbers