zoukankan      html  css  js  c++  java
  • LeetCode -- Add Two Numbers

    Question:

    You are given two linked lists representing two non-negative numbers. 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.

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

    Analysis:

    给出两个由非负整数构成的链表。数字倒序存放在链表中,对两个数相加然后返回倒序的和。例如题目中给出的例子的意思是:342+465 = 807.

    刚开始做时发现,243 + 564 = 807,因此以为正序加与反序加效果一样,但后来有很多情况并不适用。

    解题思路:首先对两个两边进行就地转置,然后将表示的数字相加(用long型保存);然后对和反序保存并返回。

    Answer:

    /**
     * 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) {
            long lo1 = 0, lo2 = 0;
            ListNode h1 = reverseList(l1), h2 = reverseList(l2);
            while(h1 != null) {
                lo1 = lo1 * 10 + h1.val;
                h1 = h1.next;
            }
            while(h2 != null) {
                lo2 = lo2 * 10 + h2.val;
                h2 = h2.next;
            }
            long sum = lo1 + lo2;
            ListNode head = new ListNode(0);
            h1 = head;
            if(sum == 0) {
                return head;
            }
            while(sum != 0) {
                int val = (int) (sum % 10);
                ListNode li = new ListNode(val);
                sum = sum / 10;
                h1.next = li;
                h1 = li;
            }
            
            return head.next;
        }
        
        public ListNode reverseList(ListNode head) {
            if(head == null || head.next == null)
                return head;
            ListNode h = head;
            while(head.next != null) {
                ListNode p = head.next;
                head.next = p.next;
                p.next = h;
                h = p;
            }
            return h;
        }
    }
  • 相关阅读:
    P1964 【mc生存】卖东西
    到达型01背包---P1877 [HAOI2012]音量调节
    组合数学---P1358 扑克牌
    分组背包---P1757 通天之分组背包
    01背包---P2392 kkksc03考前临时抱佛脚
    背包DP 方案数
    完全背包---P1679 神奇的四次方数
    01-背包---P2663 越越的组队
    17、排序算法-希尔排序
    16、排序算法-插入排序
  • 原文地址:https://www.cnblogs.com/little-YTMM/p/4796008.html
Copyright © 2011-2022 走看看