1. 程式人生 > 其它 >Leetcode 2. Add Two Numbers

Leetcode 2. Add Two Numbers

Leetcode 2. Add Two Numbers

這道題比較簡單,主要練練手,通過這道題可以看到 leetcode 官方對於不同語言的連結串列的定義,瞭解不同語言之間的差異,特別是關於 Swift 的 nilvarlet 處理。

C++

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {

        ListNode *head = new ListNode();
        ListNode *rear = head;
        int carry = 0;
        while(l1 != nullptr || l2 != nullptr) {
            int val1 = l1 == nullptr ? 0 : l1->val;
            int val2 = l2 == nullptr ? 0 : l2->val;
            int sum = val1 + val2 + carry;
            int residue = sum % 10;
            carry = sum / 10;
            rear->next = new ListNode(residue);
            rear = rear->next;
            if(l1 != nullptr) l1 = l1->next;
            if(l2 != nullptr) l2 = l2->next;
        }

        if(carry > 0) {
            rear->next = new ListNode(carry);
        }

        return head->next;
    }
};

Ruby

# Definition for singly-linked list.
# class ListNode
#     attr_accessor :val, :next
#     def initialize(val = 0, _next = nil)
#         @val = val
#         @next = _next
#     end
# end
# @param {ListNode} l1
# @param {ListNode} l2
# @return {ListNode}
def add_two_numbers(l1, l2)
    head = rear = ListNode.new

    carry = 0
    while l1 or l2 do
        val1 = l1.nil? ? 0 : l1.val
        val2 = l2.nil? ? 0 : l2.val
        sum = val1 + val2 + carry
        residue = sum % 10
        carry = sum / 10
        rear.next = ListNode.new(residue)
        rear = rear.next

        l1 = l1.next if l1
        l2 = l2.next if l2
    end

    if carry > 0
        rear.next = ListNode.new(carry)
    end

    head.next
end

Python

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
        head = rear = ListNode()
        carry = 0
        while l1 or l2:
            val1 = l1.val if l1 else 0
            val2 = l2.val if l2 else 0

            sum = carry + val1 + val2
            residue = sum % 10
            carry = sum // 10

            rear.next = ListNode(residue)
            rear = rear.next

            l1 = l1.next if l1 else l1
            l2 = l2.next if l2 else l2

        if carry > 0:
            rear.next = ListNode(carry)

        return head.next

Swift

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     public var val: Int
 *     public var next: ListNode?
 *     public init() { self.val = 0; self.next = nil; }
 *     public init(_ val: Int) { self.val = val; self.next = nil; }
 *     public init(_ val: Int, _ next: ListNode?) { self.val = val; self.next = next; }
 * }
 */
class Solution {
    
    func addTwoNumbers(_ l1:ListNode?, _ l2:ListNode?) -> ListNode? {
        let head = ListNode()
        var rear = head

        var carry = 0 //進位控制
        
        var tp1 = l1, tp2 = l2

        while tp1 != nil  ||  tp2 != nil {
            let x = tp1?.val ?? 0
            let y = tp2?.val ?? 0

            let sum = x + y + carry
            carry = sum / 10 //進位
            
            rear.next = ListNode.init(sum % 10)
            rear = rear.next!
            if tp1 != nil {
                tp1 = tp1?.next
            }
            if tp2 != nil {
                tp2 = tp2?.next
            }
            // 導致死迴圈  -- Why
            //tp1 = tp1?.next ?? tp1
            //tp2 = tp2?.next ?? tp2
        }
        
        if carry > 0 {//最後兩數相加,如果有進位,也要加上
            rear.next = ListNode.init(carry)
        }
        
        return head.next
    }
}