Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Autosaved

...

https://leetcode.com/problems/add-two-numbers-ii/

Code Block
languagego
/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
    nodes1 := fromList(l1)
    nodes2 := fromList(l2)
    
    result := add(nodes1, nodes2)
    
    return toList(result)
}

func add(nodes1, nodes2 []int) []int {
    result := make([]int, 0, 101)
    
    p1, p2 := 0, 0
    carry := 0
    
    for p1 < len(nodes1) || p2 < len(nodes2) || carry > 0 {
        val := carry
        if p1 < len(nodes1) {
            val += nodes1[p1]
            p1++
        }
        if p2 < len(nodes2) {
            val += nodes2[p2]
            p2++
        }
        
        if val >= 10 {
            val -= 10
            carry = 1
        } else {
            carry = 0
        }
        
        result = append(result, val)
    }
    
    return result
}

func fromList(h *ListNode) []int {
    nodes := make([]int, 0, 100)
    for h != nil {
        nodes = append(nodes, h.Val)
        h = h.Next
    }
    
    reverse(nodes)
    
    return nodes
}

func toList(nodes []int) *ListNode {
    reverse(nodes)
    
    dummy := &ListNode{}
    
    h := dummy
    for _, num := range nodes {
        h.Next = &ListNode{Val: num}
        h = h.Next
    }
    
    return dummy.Next
}

func reverse(arr []int) {
    i, j := 0, len(arr)-1
    for i < j {
        arr[i], arr[j] = arr[j], arr[i]
        i++
        j--
    }
}

丑数

LC 313. 超级丑数

https://leetcode.com/problems/super-ugly-number/

Code Block
languagego

LC 1201. 丑数 III