zoukankan      html  css  js  c++  java
  • LeetCode 2. Add Two Numbers (两数相加)

    题目标签:Linked List, Math

      题目给了我们两个 Linked List, 各代表一个数字,不过顺序的反的。让我们把两个数字相加。

      和普通的相加其实差不多,只不过变成了 Linked List, 还是要用到 / 和 %,具体看code。

    Java Solution:

    Runtime:  2ms, faster than 87% 

    Memory Usage: 44MB, less than 85%

    完成日期:07/05/2019

    关键点:利用 / 取得 carry;利用 % 取得 余数

    /**
     * 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 dummyHead = new ListNode(0);
            ListNode cursor1 = l1;
            ListNode cursor2 = l2;
            ListNode cursor3 = dummyHead;
            
            int carry = 0;
            
            while(cursor1 != null || cursor2 != null) // go through both list
            {
                // if node exists, get the value, elsewise, default 0
                int num1 = 0;
                int num2 = 0;
                
                if(cursor1 != null)
                    num1 = cursor1.val;
                if(cursor2 != null)
                    num2 = cursor2.val;
                
                
                int sum = num1 + num2 + carry;
                
                // update carry and sum
                carry = sum / 10;
                cursor3.next = new ListNode(sum % 10);
                cursor3 = cursor3.next;
                
                // move both list to next node
                if(cursor1 != null)
                    cursor1 = cursor1.next;
                if(cursor2 != null)
                    cursor2 = cursor2.next;
            }
            
            // at last, still need to check carry for last digit
            if(carry == 1)
                cursor3.next = new ListNode(1);
            
            return dummyHead.next;
        }
    }

    参考资料:N/A

    LeetCode 题目列表 - LeetCode Questions List

    题目来源:https://leetcode.com/

  • 相关阅读:
    Linux基础篇之软件源码包安装
    11-1 网络协议和管理
    bash-2 httpd服务的源码编译安装脚本
    8-1 文本三级剑客之sed
    9-3 磁盘存储与分区
    9-2 yum,dnf和apt
    9-1 软件包管理
    bash-1 初始化CentOS系统的初始化脚本
    3-3 man手册介绍
    5-3 文件权限
  • 原文地址:https://www.cnblogs.com/jimmycheng/p/11144963.html
Copyright © 2011-2022 走看看