力扣刷题之玩转ChatGPT(二、两数相加)

1. 两数相加

题目描述:给定两个非空链表来表示两个非负整数,位数按照逆序方式存储,并且每个节点只能存储一位数字。求这两个数相加起来的结果,并以相同形式返回一个表示和的链表。

例如,输入的链表 1->2->3 和 4->5->6,输出的结果为 5->7->9。

解题思路:

这道题可以用简单的模拟法来解决。由于链表中数字按照逆序的方式存储,我们可以使用两个指针分别遍历两个链表,同时维护一个进位的变量carry,将两个节点的值以及进位相加,得到新的节点值,然后更新进位的值,并将新节点加入到答案链表中。

需要注意的是,当两个链表长度不同时,遍历链表时较短的链表后面缺失的节点视为0,保证两个链表能够全部遍历到。

Java代码:
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    ListNode dummy = new ListNode(0);
    ListNode cur = dummy;
    int carry = 0;
    while (l1 != null || l2 != null) {
        int x = (l1 != null) ? l1.val : 0;
        int y = (l2 != null) ? l2.val : 0;
        int sum = carry + x + y;
        carry = sum / 10;
        cur.next = new ListNode(sum % 10);
        cur = cur.next;
        if (l1 != null) l1 = l1.next;
        if (l2 != null) l2 = l2.next;
    }
    if (carry > 0) {
        cur.next = new ListNode(carry);
    }
    return dummy.next;
}

Python代码:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
    dummy = ListNode(0)
    cur = dummy
    carry = 0
    while l1 or l2:
        x = l1.val if l1 else 0
        y = l2.val if l2 else 0
        sum = carry + x + y
        carry = sum // 10
        cur.next = ListNode(sum % 10)
        cur = cur.next
        if l1: l1 = l1.next
        if l2: l2 = l2.next
    if carry > 0:
        cur.next = ListNode(carry)
    return dummy.next


C语言代码:
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2){
    struct ListNode *dummy = (struct ListNode *)malloc(sizeof(struct ListNode));
    struct ListNode *cur = dummy;
    int carry = 0;
    while (l1 || l2) {
        int x = (l1) ? l1->val : 0;
        int y = (l2) ? l2->val : 0;
        int sum = carry + x + y;
        carry = sum / 10;
        cur->next = (struct ListNode*)malloc(sizeof(struct ListNode));
        cur->next->val = sum % 10;
        cur = cur->next;
        if (l1) l1 = l1->next;
        if (l2) l2 = l2->next;
    }
    if (carry > 0) {
        cur->next = (struct ListNode*)malloc(sizeof(struct ListNode));
        cur->next->val = carry;
        cur = cur->next;
    }
    cur->next = NULL;
    return dummy->next;
}


以上三份代码时间复杂度均为O(max(m, n)),其中m和n分别是两个链表的长度。由于这个问题能够用简单的模拟法解决,因此在大多数情况下此方法已经足够高效。

以上文章内容均由ChatGPT3.5版本给出的作答,有问题可以提出来一起探讨!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值