Leetcode第二題解題java實現

來源:互聯網
上載者:User
問題:

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 審題:

該題把數字按位拆開以倒序方式存放在一個鏈表中,要求計算兩個數位和,以同樣的方式返回。該題的考察點是鏈表的遍曆,他以倒序儲存數字,減低瞭解題的繁瑣程度,想象一下,分別從兩個鏈表中同時取出一個數,比如第一個,這兩數都是個位上的數,直接相加即可,得到的數看是否有進位,把進位值記下。
我的想法是把兩個鏈表的數挨個遍曆取出,沒取出一位元就相加再加進位,並對10求餘,存到另外一個鏈表的節點中,取整得到進位,存起來,
一直迴圈到兩鏈表為空白。 解題:

/** * 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) {        if(l1 == null && l2 == null)        {            return null;        }        ListNode lhead;        ListNode l = new ListNode(0);        lhead = l;        int flag=0;        while(l1!=null || l2!=null)        {            ListNode lnext = new ListNode(0);            int a = l1==null?0:l1.val;            int b = l2==null?0:l2.val;            lnext.val = (a+b+flag)%10;            flag = (a+b+flag)/10;            l.next = lnext;            l = l.next;            l1 = l1==null?null:l1.next;            l2 = l2==null?null:l2.next;        }        if(flag != 0)    //如果還有進位,添加節點存入其中        {            ListNode lnext = new ListNode(0);            lnext.val = flag;            l.next = lnext;        }        return lhead.next;    }}

該解題思維相對正常,是靠生活計算經驗解題,沒有複雜演算法,排名置中。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.