1. 程式人生 > >【LeetCode】Add Two Numbers Go語言實現

【LeetCode】Add Two Numbers Go語言實現

問題描述

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

大意就是兩個連結串列相加,輸出結果連結串列。

思路

模擬平時列豎式做加法運算的過程即可。有幾個點需要考慮:

  • 進位的儲存。因為最大隻能是 9 + 9 = 18,所以進位只可能為 0 或 1
  • 2位整數取最低位。直接除以10即可。
  • 最高位的進位。 如 L1 = 9, L2 = 1, 這時結果表L3 = 10, 比L1, L2多一個結點

Go實現

用時26ms, 擊敗了85%(用golang的)人

func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
    // 進位值, 只可能為0或1
    promotion := 0

    // 結果表的頭結點
    var
head *ListNode // 儲存結果表的尾結點 var rear *ListNode for nil != l1 || nil != l2 { sum := 0 if nil != l1 { sum += l1.Val l1 = l1.Next } if nil != l2 { sum += l2.Val l2 = l2.Next } sum += promotion promotion = 0
if sum >= 10 { promotion = 1 sum = sum % 10 } node := &ListNode{ sum, nil, } if nil == head { head = node rear = node } else { rear.Next = node rear = node } } if promotion > 0 { rear.Next = &ListNode{ promotion, nil, } } return head }