【LeetCode】Add Two Numbers 解題報告 (Java),leetcodenumbers

來源:互聯網
上載者:User

【LeetCode】Add Two Numbers 解題報告 (Java),leetcodenumbers

【題目】

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

【說明】

這道題不難,思路很直觀,考基本功。

遍曆兩個鏈表時必須的,需要注意的是最後一個結點如果有進位,需要new一個結點。

網上很多代碼是重新new一個鏈表來存放結果,我覺得可以直接用 l1 來存放結果。

網上很多代碼看起來更短,但時間複雜度並沒有降低,為便於理解,我覺著還是下面寫的比較清晰。

【Java代碼】

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { *         val = x; *         next = null; *     } * } */public class Solution {    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {        if (l1 == null) return l2;        if (l2 == null) return l1;                //把相加後的結果存放於鏈表1,pre1是用於最後有進位時在其後new新結點        ListNode ret = l1;        ListNode pre1 = new ListNode(0);        pre1.next = l1;                int flag = 0;        while (l1 != null && l2 != null) {            l1.val = l1.val + l2.val + flag;            flag = l1.val / 10;            l1.val = l1.val % 10;            pre1 = l1;            l1 = l1.next;            l2 = l2.next;        }                //如果鏈表2有剩餘,接到鏈表1的後面        if (l2 != null) {            pre1.next = l2;            l1 = l2;        }                while (l1 != null) {            l1.val += flag;            flag = l1.val / 10;            l1.val = l1.val % 10;            pre1 = l1;            l1 = l1.next;        }                if (flag > 0) {            ListNode node = new ListNode(1);            pre1.next = node;        }                return ret;    }}



Add two numbers to 19 and make it less than 20How can it be?

because x+y+19<20 SO x+y<1 SO x<1-y
 
Java native(JNI)問題教!

使用System.loadLibrary同時把dll加入系統path
雖然這個方法比較笨拙
不過應該能解決問題,呵呵
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.