zoukankan      html  css  js  c++  java
  • [LeetCode] 2. Add Two Numbers ☆☆

    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.

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

    解法: 建立一个新链表,然后把输入的两个链表从头往后撸,每两个相加,添加一个新节点到新链表后面,注意要处理下进位问题。还有就是最高位的进位问题要最后特殊处理一下(这一步容易忽略!)。时间复杂度为O(n),空间复杂度为O(n)。

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            ListNode result = new ListNode(-1);  // 方便后续操作,最终返回result.next即可
            ListNode currNode = result;
            int carry = 0;  // 进位1,不进位0
            
            while ((l1 != null) || (l2 != null)) {
                int d1 = l1 == null ? 0 : l1.val;
                int d2 = l2 == null ? 0 : l2.val;
                int sum = d1 + d2 + carry;
                carry = sum > 9 ? 1 : 0;
                
                currNode.next = new ListNode(sum % 10);
                currNode = currNode.next;
                if (l1 != null) l1 = l1.next;
                if (l2 != null) l2 = l2.next;
            }
            
            if (carry == 1) {
                currNode.next = new ListNode(1);
            }
            
            return result.next;
        }
    }

    ps: 不要采用先计算出两个链表的数后相加,最后将和用链表表示的算法。因为链表的长度可能很长,不一定能用int或double表示。

  • 相关阅读:
    MS SQL执行大脚本文件时,提示“未能完成操作,存储空间不足,无法处理此命令”的解决办法
    一、Flux 是什么?
    for...in for..of
    循环总结
    javascript中几种this指向问题
    redux
    布局方式
    js获取前几个月的具体日期
    动态引入js文件
    获取页面url信息
  • 原文地址:https://www.cnblogs.com/strugglion/p/6383552.html
Copyright © 2011-2022 走看看