002 Add Two Numbers [Leetcode]
来源:互联网 发布:纠正英语发音的软件 编辑:程序博客网 时间:2024/05/17 06:22
题目内容:
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
解题思路:
没什么技巧,注意进位即可(包括每一位进位与最高位进位)。
class Solution {public: ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) { if(l1 == NULL && l2 == NULL) return NULL; else if(l1 == NULL) return l2; else if(l2 == NULL) return l1; bool carry = false; ListNode *head = new ListNode(0), *curr = head; while(l1 != NULL && l2 != NULL) { curr->next = addDigit(l1->val, l2->val, carry); curr = curr->next; l1 = l1->next; l2 = l2->next; } if(l1 == NULL) l1 = l2; while(carry && l1 != NULL) { curr->next = addDigit(l1->val, 0, carry); curr = curr->next; l1 = l1->next; } if(carry) curr->next = new ListNode(1); copyList(curr, l1); curr = head; head = head->next; delete curr; return head; } void copyList(ListNode *l1, ListNode *l2) { while(l2 != NULL) { l1->next = new ListNode(l2->val); l1 = l1->next; l2 = l2->next; } } ListNode *addDigit(int val1, int val2, bool &carry) { int val(val1 + val2); if(carry) { ++val; carry = false; } if(val >= 10) { val -= 10; carry = true; } return new ListNode(val); }};
0 0
- 【leetcode】002 Add Two Numbers
- LeetCode 002 Add Two Numbers
- LeetCode 002-Add Two Numbers
- [LeetCode]-002-Add Two Numbers
- LeetCode #002 Add Two Numbers
- LeetCode 002, Add Two Numbers
- 002 Add Two Numbers [Leetcode]
- LeetCode 002 Add Two Numbers
- 002 Add Two Numbers [Leetcode]
- LeetCode #002 Add Two Numbers
- LeetCode 002 Add Two Numbers
- leetcode-002 Add Two Numbers
- 【Leetcode】002 Add Two Numbers
- LeetCode-002 Add Two Numbers
- leetcode 002 Add Two Numbers
- LeetCode: Add Two Numbers
- LeetCode: Add Two Numbers
- [LeetCode]Add Two Numbers
- 错误: -source 1.6 中不支持 diamond 运算符 (请使用 -source 7 或更高版本以启用 diamond 运算符)
- Linux IPC实践--Posix消息队列
- SYN攻击实现
- Goovy 脚本编程的学习之路
- 欢迎使用CSDN-markdown编辑器
- 002 Add Two Numbers [Leetcode]
- OpenGL ES(5)——添加动作
- PV、UV、IP的区别
- AndroidStudio library module的R文件报错
- libzplay库
- 深度学习算法原理——稀疏自编码器
- LeetCode(143) Reorder List
- tesseract-ocr识别中文扫描图片实例讲解
- spring4如何整合hibernate4