zoukankan      html  css  js  c++  java
  • Leetcode 2. Add Two Numbers

    题目链接

    https://leetcode.com/problems/add-two-numbers/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.

    Example:

    
    Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
    Output: 7 -> 0 -> 8
    Explanation: 342 + 465 = 807.
    
    

    题解

    依次遍历两个链表,计算对应位的和,如果有进位,计算进位。

    XBB Time:刚开始写的check函数是把当前节点的前一个节点(记为pre),带进函数里面的,但是总是过不了,感觉是复制了一份传入,函数内的修改了值,但是外层函数中的pre并没有变,这就又回到了到底是值传递还是引用传递,其实是把引用复制了一份,然后传递进去,操作的是同一个内存地址,对该内存地址的修改是可见的,但是函数里的pre已经指向其他的地址了,外层函数的pre是不会变的。

    代码

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    class Solution {
        int count = 0;
        ListNode start = new ListNode(0);
        ListNode pre = start;
        public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            while (l1 != null && l2 != null) {
                int val = l1.val + l2.val + count;
                count = val / 10;
                ListNode node = new ListNode(val % 10);
                pre.next = node;
                pre = node;
                l1 = l1.next;
                l2 = l2.next;
            }
            // check(l1, pre);
            // check(l2, pre);
            check(l1);
            check(l2);
            if (count != 0) {
                ListNode node = new ListNode(count);
                pre.next = node;
                pre = node;
            }
            return start.next;
        }
        
        /**
        * 开始把count带入了函数,有的用例过不了,count是值传递
        **/
        public void check(ListNode l) {
            while (l != null) {
                if (count == 0) {
                    pre.next = l;
                    break;
                }
                int val = l.val + count;
                count = val / 10;
                ListNode node = new ListNode(val % 10);
                pre.next = node;
                pre = node;
                l = l.next;
            }
        }
    }
    
    
  • 相关阅读:
    CentOS75 安装 telnet 进行使用.
    Windows 创建计划任务 实现自动同步文件.
    qemu-img.exe 工具 简介
    中建项目环境迁移说明
    服务器内存最大大小限制
    bzip2 以及 tar 压缩/解压缩/.打包等工具软件
    Ubuntu18.04 安装后的简单实用设置[未完成]
    oracle 启动监听报错TNS-12547: TNS:lost contact
    Linux审计sudo
    OPENVAS运行
  • 原文地址:https://www.cnblogs.com/xiagnming/p/9639747.html
Copyright © 2011-2022 走看看