Leetcode:2. Add Two Numbers(Week 6)
来源:互联网 发布:基于大数据用户画像 编辑:程序博客网 时间:2024/05/16 05:01
Description:
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
解题分析:
将两个非空链表从头到尾依次相加,得到一个新的链表,链表上的值为和的个位数,若和超过10则将和/10
的结果(即进位)参与下一个节点的相加,重复上述操作直到较长链表结尾。
代码如下:
/** * 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 *prev = NULL, *result = NULL; int carry = 0; while (l1 || l2) { int v1 = l1? l1->val : 0; int v2 = l2? l2->val : 0; int sum = v1+v2 + carry; int value = sum%10; carry = sum/10; ListNode * cur = new ListNode(value); if (!result) result = cur; if (prev) prev->next = cur; prev = cur; l1 = l1 ? l1->next :NULL; l2 = l2 ? l2->next : NULL; } if (carry > 0) { ListNode * l = new ListNode(carry); prev->next = l; } return result; }};
阅读全文
0 0
- Leetcode:2. Add Two Numbers(Week 6)
- LeetCode题解(Week 3):445. Add Two Numbers II
- [LeetCode]2.Add Two Numbers
- LeetCode 2.Add Two Numbers
- LeetCode --- 2. Add Two Numbers
- [Leetcode] 2. Add Two Numbers
- 【leetcode】2. Add Two Numbers
- leetcode 2. Add Two Numbers
- LeetCode-2.Add Two Numbers
- [leetcode] 2. Add Two Numbers
- 【LeetCode】2. Add Two Numbers
- LeetCode - 2. Add Two Numbers
- LeetCode 2.Add Two Numbers
- LeetCode 2. Add Two Numbers
- Leetcode 2. Add Two Numbers
- 2. Add Two Numbers LeetCode
- leetcode 2. Add Two Numbers
- LeetCode-2. Add Two Numbers
- org.springframework.beans.factory.BeanCreationException: Error...... java.lang.IllegalArgumentExcept
- rpm命令
- sdut 2135 数据结构实验之队列一:排队买饭
- Java利用栈解决符号匹配问题
- spring boot 集成mongo配置
- Leetcode:2. Add Two Numbers(Week 6)
- Java中单例模式
- PHP编译参数
- 【深度学习】使用tensorflow实现VGG19网络
- Vivado中仿真DDS核注意事项即仿真IP核时需要注意的事项
- AJAX
- <并查集>luogu 1197 星球大战
- 第五周 项目1
- OkHttp接入HttpDNS,最佳实践