LeetCode OJ (2)
来源:互联网 发布:剑灵龙男捏脸数据大全 编辑:程序博客网 时间:2024/06/14 12:49
Add Two Numbers
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
初始代码块(初学者水平)
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { ListNode *header=NULL,*sum=NULL; int carry=0; bool flag=false; while(l1!=NULL && l2!=NULL){ ListNode *tmp=new ListNode(0); carry=l1->val+l2->val+flag; if(carry>=10){ tmp->val = carry-10; flag = true; } else{ tmp->val=carry; flag=false; } if(!header) header=tmp; else sum->next=tmp; sum=tmp; l1=l1->next; l2=l2->next; } ListNode *last; if(l1==NULL) last=l2; else last=l1; carry=0; while(last!=NULL){ ListNode *tmp=new ListNode(0); carry=last->val+flag; if(carry>=10){ tmp->val=carry-10; flag=true; } else{ tmp->val=carry; flag=false; } sum->next=tmp; sum=tmp; last=last->next; } if(flag){ ListNode *tmp=new ListNode(0); tmp->val=flag; sum->next=tmp; } return header;}}
经过优化和学弟提醒之后
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { ListNode *header=NULL,*sum=NULL; int carry=0; while(l1 || l2){ new ListNode(0); if(l1) carry+=l1->val; if(l2) carry+=l2->val; ListNode *tmp=new ListNode(carry%10); if(!header) header=tmp; else sum->next=tmp; carry/=10; sum=tmp; if(l1) l1=l1->next; if(l2) l2=l2->next; } if(carry){ ListNode *tmp=new ListNode(carry); sum->next=tmp; } return header;}
我太悲伤了,第二个代码块是我奋斗的目标!
0 0
- leetcode oj 2
- LeetCode OJ (2)
- LeetCode-OJ
- leetcode oj
- LeetCode OJ:Search a 2D Matrix
- LeetCode OJ - Search a 2D Matrix
- [LeetCode OJ]Search a 2D Matrix
- LeetCode OJ Search a 2D Matrix
- LeetCode OJ #2 Add Two Numbers
- LeetCode OJ : 2 Add Two Numbers
- 笔试题15. LeetCode OJ (2)
- LeetCode OJ | Search a 2D Matrix
- Leetcode OJ 2 Add Two Numbers [Medium]
- 【LeetCode OJ】Combinations
- 【LeetCode OJ】Valid Parentheses
- [LeetCode OJ]Single Number
- [LeetCode OJ]Same Tree
- LeetCode OJ:Single NumberII
- spark-submit 运行参数问题记录
- 【map的lower_bound up, 与erase】stl
- 阿里云文件迁移工具使用小结
- 周鸿祎:真想不通是张小龙这样的人做出了微信!
- 【bzoj4152】【AMPPZ2014】The Captain
- LeetCode OJ (2)
- 什么是交叉编译,为什么要使用交叉编译?
- srs代码学习(7)--消息接收过程
- java 对象 和 json 之间互转 例子
- POJ 1221 UNIMODAL PALINDROMIC DECOMPOSITIONS
- MySQL出现Errcode:28错误提示解决办法
- Linux存储IO栈(1)-- 内核对象与对象集
- 链表的使用
- C++ 类的使用