LeetCode——2. 两数相加(给你两个 非空 的链表,表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储)

题目要求

  • 给你两个 非空 的链表,表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的,并且每个节点只能存储 一位 数字。

  • 请你将两个数相加,并以相同形式返回一个表示和的链表。

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

  • 每个链表中的节点数在范围 [1, 100] 内

  • 0 <= Node.val <= 9

  • 题目数据保证列表表示的数字不含前导零
    在这里插入图片描述

一、我自己的解法(暴力解)

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public int getLength(ListNode listNode) {
        int i = 1;
        while (listNode.next != null) {
            i++;
            listNode = listNode.next;
        }
        return i;
    }

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        int l1Length = getLength(l1);
        int l2Length = getLength(l2);
        int middle = Math.max(l1Length, l2Length) - Math.min(l1Length, l2Length);
        int add = 0; //进位
        StringBuilder nums = new StringBuilder("");
        int shortLength = Math.min(l1Length, l2Length);
        for (int i = shortLength; i > 0; i--) {
            int num = l1.val + l2.val+add;
            if (num>=10){
                add = 1;
                nums.append(num-10);
            }else{
                add = 0;
                nums.append(num);
            }
            l1=l1.next;
            l2=l2.next;
        }
        ListNode longNode = l1Length>l2Length?l1:l2;
        if (middle >= 0){
            for (int i = 0; i < middle; i++) {
                int a = longNode.val+add;
                if (a>=10){
                    add = 1;
                    nums.append(a-10);
                }else{
                    add = 0;
                    nums.append(a);
                }
                    longNode=longNode.next;
            }
            if (add == 1){
                nums.append(1);
            }
        }

        String s = nums.toString();
        ListNode ll1 = new ListNode(Integer.parseInt(s.substring(0, 1)), null);
        int y = 1;
        ListNode tem = ll1;
        while (y < s.length()) {
            tem.next = new ListNode(Integer.parseInt(s.substring(y, y + 1)), null);
            tem = tem.next;
            y += 1;
        }
        return ll1;

    }
}

二、比较好的解法

public class B_Solution {
    public static void main(String[] args) {

    }
    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode dummy = new ListNode(0);
        int sum = 0;    //结果
        int more = 0;   //进位
        ListNode pre = dummy;
        while (l1 != null || l2 != null || more > 0){
            sum = (l1 == null?0:l1.val) + (l2 == null?0:l2.val) + more;
            more = sum / 10;  //判断有无进位
            sum %= 10;        //如果大于10,就进上去了,留下余数
            ListNode node = new ListNode(sum); //新的一个节点,存储计算出来的值
            pre.next = node;  //把他替换为这个新的节点
            pre = node;
            l1 = l1 == null ? null : l1.next;
            l2 = l2 == null ? null : l2.next;
        }
        return dummy.next;
    }
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
```cpp #include <iostream> using namespace std; 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) {} }; ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { ListNode* dummy = new ListNode(0); ListNode* curr = dummy; int carry = 0; while (l1 != nullptr || l2 != nullptr) { int x = (l1 != nullptr) ? l1->val : 0; int y = (l2 != nullptr) ? l2->val : 0; int sum = x + y + carry; carry = sum / 10; curr->next = new ListNode(sum % 10); curr = curr->next; if (l1 != nullptr) { l1 = l1->next; } if (l2 != nullptr) { l2 = l2->next; } } if (carry > 0) { curr->next = new ListNode(carry); } return dummy->next; } int main() { // 创建链表 l1: 2 -> 4 -> 3 ListNode* l1 = new ListNode(2); l1->next = new ListNode(4); l1->next->next = new ListNode(3); // 创建链表 l2: 5 -> 6 -> 4 ListNode* l2 = new ListNode(5); l2->next = new ListNode(6); l2->next->next = new ListNode(4); // 调用函数进行相加 ListNode* result = addTwoNumbers(l1, l2); // 输出结果链表 while (result != nullptr) { cout << result->val << " "; result = result->next; } return 0; } ``` 这段C++代码实现了将两个存储整数链表相加,并以相同形式返回一个表示和的链表。首先,我们定义了一个`ListNode`结构体来表示链表节点。然后,我们实现了`addTwoNumbers`函数来进行链表相加的操作。在函数中,我们使用了一个`dummy`节点作为结果链表的头节点,并使用一个`curr`指针来指向当前节点。我们还定义了一个`carry`变量来保存进位值。在循环中,我们依次遍历两个链表的节点,并将对应位置的数字相加,再加上进位值。然后,我们将相加结果的个位数作为新节点的值,并更新进位值。最后,如果还有进位值,我们在结果链表的末尾添加一个新节点。最后,我们返回结果链表的头节点。 以上是一种C++实现的方式,你可以根据需要进行调整和修改。 #### 引用[.reference_title] - *1* [它们每位数字都是按照 方式存储的,并且每个节点只能存储 一位 数字。 请你将两个数相加,并以相同...](https://blog.csdn.net/m0_56183819/article/details/124357484)[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^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [Leetcode 2.两数相加 两个链表表示两个整数。它们每位数字都是按照方式存储的。](https://blog.csdn.net/qfxl0724/article/details/126048497)[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^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [它们每位数字都是按照 方式存储的,并且每个节点只能存储 一位 数字。请你将两个数相加,并以相同...](https://blog.csdn.net/m0_50672338/article/details/127810149)[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^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Java天下第1

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值