每日一則 LeetCode: 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.java

You may assume the two numbers do not contain any leading zero, except the number 0 itself.node

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

中文解釋

給定兩個非空的鏈表裏面分別包含不等數量的正整數,每個節點都包含一個正整數,肯能是0,可是不會是01這種狀況。咱們須要按照倒序計算他們的和而後再次倒序輸出。git

解題思路

這題沒有什麼巧妙的方式,不過仔細思考一下,它實際上是在模擬正常的多位數加法。咱們試想在計算多位數加法的時候,從最末位開始計算,若是大於10就進位,並加到下次高位計算中;若是不大於10繼續計算;就這樣咱們就有了下面的階梯思路。
一次循環就能夠搞定,經過判斷他們其中是否是空,就像是多位數加減法,若是一個高位沒有了,固然也要繼續計算,因此有了下面默認 int carry = 0,而後經過 sum / 10 算出進位,經過 sum % 10 算出當前位,這個題就迎刃而解。微信

源碼

public class AddTwoNumbers {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode tempNode = new ListNode(0);
        ListNode a = l1, b = l2, curr = tempNode;
        int carry = 0;
        while (a != null || b != null) {
            int x = a != null ? a.val : 0;
            int y = b != null ? b.val : 0;
            int sum = carry + x + y;
            carry = sum / 10;
            curr.next = new ListNode(sum % 10);
            curr = curr.next;
            if (a != null) a = a.next;
            if (b != null) b = b.next;
        }

        if (carry > 0) {
            curr.next = new ListNode(carry);
        }

        return tempNode.next;
    }

    public static void main(String[] args) {
        ListNode l1 = new ListNode(2);
        l1.add(new ListNode(4));
        l1.add(new ListNode(3));
        ListNode l2 = new ListNode(5);
        l2.add(new ListNode(6));
        l2.add(new ListNode(4));
        ListNode listNode = new AddTwoNumbers().addTwoNumbers(l1, l2);
        System.out.println(listNode.val);
        while (listNode.next != null) {
            System.out.println(listNode.next.val);
            listNode = listNode.next;
        }
    }
}

class ListNode {
    int val;
    ListNode next;

    ListNode(int x) {
        val = x;
    }

    public void add(ListNode next) {
        ListNode last = getLast(this);
        last.next = next;
    }

    private ListNode getLast(ListNode next) {
        while (next.next != null) {
            return getLast(next.next);
        }
        return next;
    }
}

原題地址

https://leetcode.com/problems...this

做者

本文做者麻醬,歡迎討論,指正和轉載,轉載請註明出處。
若是興趣能夠關注做者微信訂閱號:碼匠筆記
微信二維碼spa

相關文章
相關標籤/搜索