【Lintcode】756. Multiply Two Numbers

題目地址:

https://www.lintcode.com/problem/multiply-two-numbers/description

給定兩個鏈表,表示十進制整數。求兩個數的乘積。直接解析出兩個整數然後相乘即可。代碼如下:

public class Solution {
    /**
     * @param l1: the first list
     * @param l2: the second list
     * @return: the product list of l1 and l2
     */
    public long multiplyLists(ListNode l1, ListNode l2) {
        // write your code here
        return compute(l1) * compute(l2);
    }
    
    private long compute(ListNode l) {
        long n = 0;
        while (l != null) {
            n *= 10;
            n += l.val;
            l = l.next;
        }
        
        return n;
    }
}

class ListNode {
    int val;
    ListNode next;
    ListNode(int x) {
        val = x;
    }
}

時間複雜度O(l1+l2)O(l_1+l_2),空間O(1)O(1)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章