Leetcode 题目002-用链表实现大数加法
2023-06-13 09:13:08 时间
解答:
c++ 版:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* root = new ListNode;
ListNode* cursor = root;
int carry = 0; //进位为1,否则为0
while(l1 || l2 || carry) {
int l1Val = l1 ? l1->val : 0;
int l2Val = l2 ? l2->val : 0;
int sumVal = l1Val + l2Val + carry;
carry = sumVal / 10; //提取十位数,0或者1
ListNode *sumNode = new ListNode(sumVal % 10);
cursor->next = sumNode;
cursor = sumNode;
if(l1) l1 = l1->next;
if(l2) l2 = l2->next;
}
return root->next;
}
};
Python 版:
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def addTwoNumbers(self, l1, l2):
root = ListNode()
cursor =root
carry = 0
while(l1 is not None or l2 is not None or carry!=0): # l1 这里等价于 l1 is not None
l1val = l1.val if l1 else 0
l2val = l2.val if l2 else 0
sumval = l1val + l2val + carry
carry = 1 if sumval > 9 else 0
sumNode = ListNode(sumval%10)
cursor.next = sumNode
cursor = sumNode
if l1 is not None: l1 = l1.next
if l2 is not None: l2 = l2.next
return root.next
相关文章
- LeetCode每日一题-1:反转链表
- LeetCode每日一题-4:合并两个有序链表
- ☆打卡算法☆LeetCode 217. 存在重复元素 算法解析
- Longest Common Prefix_LeetCode
- 【leetCode】整数反转
- leetcode之 两数之和 题目解答C/python
- LeetCode每日一题06-16
- Leetcode 题目870-优势洗牌(田忌赛马)
- Leetcode 题目069-求平方根
- 图解剑指 Offer II 024. 反转链表(LeetCode)
- LeetCode 141. 环形链表
- LeetCode 237. 删除链表中的节点
- LeetCode 66. 加一
- JavaScript刷LeetCode模板技巧篇(一)
- leetcode 206. 反转链表 js实现
- 【刷题day06】力扣(LeetCode)每日一刷[21. 合并两个有序链表][206. 反转链表 ][392. 判断子序列]
- LeetCode | 删除链表的倒数第 N 个结点
- leetcode 101. 对称二叉树 js实现
- 前端工程师leetcode算法面试必备---二分搜索算法(下)
- LeetCode 82:删除排序链表中的重复元素 II
- LeetCode 83:删除排序链表中的重复元素
- leetcode 链表初探 21. merge two sorted lists
- LeetCode-77-组合
- 【Leetcode】链表的深度拷贝——复制带随机指针的链表
- Leetcode 跳跃游戏
- LeetCode 复制带随机指针的链表(C语言)
- LeetCode 刷题常用数据结构(Java 篇)
- [数据结构]链表OJ(leetcode)
- leetcode:数组中的第K个最大元素
- LeetCode 0050 Pow(x,n)详解编程语言