2. Add Two Numbers
来源:互联网 发布:网络扫描仪怎么设置 编辑:程序博客网 时间:2024/06/11 23:47
Leet code #2 Add two numbers
刚开始刷算法题,记录一下。有更好的answer还请不吝赐教!
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { ListNode* cur1, *cur2, *tp; ListNode* result; cur1 = l1, cur2 = l2; int carry = 0, temp = 0; temp = carry + cur1->val + cur2->val; carry = temp/10; result = new ListNode(temp%10); tp = result; cur1 = cur1->next; cur2 = cur2->next; while(cur1 != NULL && cur2 != NULL) { temp = carry + cur1->val + cur2->val; carry = temp/10; tp->next = new ListNode(temp%10); tp = tp->next; cur1 = cur1->next; cur2 = cur2->next; } while(cur1 != NULL) { temp = carry + cur1->val; carry = temp/10; tp->next = new ListNode(temp%10); tp = tp->next; cur1 = cur1->next; } while(cur2 != NULL) { temp = carry + cur2->val; carry = temp/10; tp->next = new ListNode(temp%10); tp = tp->next; cur2 = cur2->next; } if(carry != 0) { tp->next = new ListNode(carry); tp = tp->next; } return result; }};
有图有真相
阅读全文
0 0
- 2.Add Two Numbers
- 2.Add Two Numbers
- 2.Add Two Numbers
- 2.Add Two Numbers
- 2. Add Two Numbers
- 2. Add Two Numbers
- 2.Add Two Numbers
- 2. Add Two Numbers
- 2. Add Two Numbers
- 2. Add Two Numbers
- 2. Add Two Numbers
- 2. Add Two Numbers
- 2. Add Two Numbers
- 2. Add Two Numbers
- 2. Add Two Numbers
- 2.Add Two Numbers
- 2. Add Two Numbers
- 2. Add Two Numbers
- 牛客网前端工程师评估笔试题总结
- 远程连接mysql 授权方法详解
- VIM使用经验
- spark源码编译、配置安装、测试
- HBase知识体系探究与整理
- 2. Add Two Numbers
- 7_27C语言|二维数组的sizeof
- html5语义化标签
- python网络爬虫 百度贴吧
- Light OJ 1004
- 搜索二叉树---之狸猫换太子的删除方法
- [leetcode]468. Validate IP Address
- opencv0-入门必知
- 浏览器不能下载response输出的excel