Add Two Numbers--LeetCode
来源:互联网 发布:济南大学网络教学平台 编辑:程序博客网 时间:2024/06/05 19:54
1.题目
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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
2.题意
给定两个非空链表,表示两个非负整数。数字以相反的顺序存储,每个节点都包含一个数字,将两个数相加,以链表形式返回。
假定两个数字不包含任何前导零,除了数字0本身。
3.分析
思路很明确,按照位数相加,维护当前位和进位即可
int n1 = l1 != nullptr ? l1->val : 0;
int n2 = l2 != nullptr ? l2->val : 0;
int sum = n1 + n2 + carry;
注意判断l1与l2是否为空,计算sum的值记得加上carry,否则会出错
4.代码
class Solution {public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { ListNode *dummy = new ListNode(-1); ListNode *cur = dummy; int carry = 0; while(l1 != nullptr || l2 != nullptr) { int n1 = l1 != nullptr ? l1->val : 0; int n2 = l2 != nullptr ? l2->val : 0; int sum = n1 + n2 + carry; carry = sum / 10; cur->next = new ListNode(sum % 10); cur = cur->next; if(l1 != nullptr) l1 = l1->next; if(l2 != nullptr) l2 = l2->next; } if(carry) cur->next = new ListNode(1); return dummy->next; }};
阅读全文
0 0
- LeetCode: Add Two Numbers
- LeetCode: Add Two Numbers
- [LeetCode]Add Two Numbers
- LeetCode Add Two Numbers
- Leetcode: Add Two Numbers
- LeetCode : Add Two Numbers
- LeetCode Add Two Numbers
- [LeetCode] Add Two Numbers
- Leetcode : Add Two Numbers
- 【leetcode】Add Two Numbers
- [LeetCode]Add Two Numbers
- leetcode Add Two Numbers
- LeetCode-Add Two Numbers
- [leetcode] Add Two Numbers
- [LeetCode] Add Two Numbers
- LeetCode - Add Two Numbers
- LeetCode | Add Two Numbers
- 【leetcode】Add Two Numbers
- svn的那些事
- java框架面试题
- 微信小程序 自定义 swiper 样式
- ubuntu换源为阿里云源
- C++中那些运算符不能重载
- Add Two Numbers--LeetCode
- jsp自定义标签的使用
- Xcode9.0+appium1.6.5真机环境运行app及遇坑知多少
- Search for a Range
- linux
- Hadoop伪分布式运行wordcount例子
- js:判断访问设备类型是什么
- java第四天/10.2
- Codeforces-868B ,C 模拟,思维。。