leetcode 两数相加c++_LeetCode #445 Add Two Numbers II 两数相加 II

442 Find All Duplicates in an Array 数组中重复的数据

Description:

You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first 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.

Follow up:

What if you cannot modify the input lists? In other words, reversing the lists is not allowed.

Example:

Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)

Output: 7 -> 8 -> 0 -> 7

题目描述:

给你两个 非空 链表来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储一位数字。将这两数相加会返回一个新的链表。

你可以假设除了数字 0 之外,这两个数字都不会以零开头。

进阶:

如果输入链表不能修改该如何处理?换句话说,你不能对列表中的节点进行翻转。

示例 :

输入:(7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)

输出:7 -> 8 -> 0 -> 7

思路:

参考LeetCode #2 Add Two Numbers 两数相加

如果不能修改原链表可以用两个栈记录每一个节点的数值, 再相加

如果可以修改原链表, 可以先计算出两个链表的长度再用递归求解

时间复杂度O(n), 空间复杂度O(n)

代码:

C++:

/**

* 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)

{

stack s1, s2;

while (l1)

{

s1.push(l1 -> val);

l1 = l1 -> next;

}

while (l2)

{

s2.push(l2 -> val);

l2 = l2 -> next;

}

int carry = 0;

ListNode *head = nullptr;

while (!s1.empty() or !s2.empty() or carry)

{

int cur = carry;

if (!s1.empty())

{

cur += s1.top();

s1.pop();

}

if (!s2.empty())

{

cur += s2.top();

s2.pop();

}

ListNode *node = new ListNode(cur % 10);

node -> next = head;

head = node;

carry = cur / 10;

}

return head;

}

};

Java:

/**

* Definition for singly-linked list.

* public class ListNode {

* int val;

* ListNode next;

* ListNode(int x) { val = x; }

* }

*/

class Solution {

public ListNode addTwoNumbers(ListNode l1, ListNode l2) {

ListNode p = l1, q = l2;

int len1 = getLength(p), len2 = getLength(q);

if (len1 < len2) return addTwoNumbers(l2, l1);

if (getCarry(l1, l2, len1 - len2) != 0) {

ListNode cur = new ListNode(1);

cur.next = l1;

l1 = cur;

}

return l1;

}

private int getLength(ListNode head) {

int result = 0;

while (head != null) {

head = head.next;

++result;

}

return result;

}

private int getCarry(ListNode l1, ListNode l2, int gap) {

if (l1 == null || l2 == null) return 0;

int s = 0;

if (gap > 0) s = l1.val + getCarry(l1.next, l2, gap - 1);

else s = l1.val + l2.val + getCarry(l1.next, l2.next, gap);

l1.val = s % 10;

return s / 10;

}

}

Python:

# Definition for singly-linked list.

# class ListNode:

# def __init__(self, x):

# self.val = x

# self.next = None

class Solution:

def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:

s1, s2 = [], []

while l1:

s1.append(l1.val)

l1 = l1.next

while l2:

s2.append(l2.val)

l2 = l2.next

carry, head = 0, None

while s1 or s2 or carry:

cur = (s1.pop() if s1 else 0) + (s2.pop() if s2 else 0) + carry

node = ListNode(cur % 10)

node.next, head, carry = head, node, cur // 10

return head

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
根据引用,题目来源于力扣(LeetCode)的Add Two Numbers问题。根据引用,这是一个关于链表的问题,给定了两个非空的链表,表示两个非负的整数。这两个链表的每个节点都存储了一个逆序的数字,并且每个节点只能存储一位数字。我们需要将这两个数相加,并以相同形式返回一个表示和的链表。除了数字0以外,这两个数不会以0开头。根据引用,这是一道高频题,互联网大厂在笔试和面试中经常会考到这类问题。解决这道题需要基础的数据结构与算法知识,并锻炼解题能力。 问题:leetcode两数相加 回答:这个问题是力扣(LeetCode)上的Add Two Numbers问题,要求计算两个逆序表示的非负整数的和,并返回以相同形式表示的链表。它是一道高频题,经常在互联网大厂的笔试和面试中出现。为了解决这个问题,需要使用链表的基本操作,并且要注意进位的处理。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [LeetCode高频题2:两数相加](https://blog.csdn.net/weixin_46838716/article/details/125237688)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] - *2* [leetcode两数相加](https://blog.csdn.net/weixin_43199244/article/details/115759341)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值