Problem List

Add Two Numbers

May 27, 2025Go linked list, math, recursionmedium

My immediate instict for this problem upon seeing the examples was to convert the linked list to a number, or sum. And for this I remembered the mathematical pattern that I also used in 9. Palindrome Number.

Take 342 for example:

If this were in a linked list, for this problem, its linked list representation would be 2 -> 4 -> 3. Similar to the palindrome number problem, I simply take the the number given times 10 to the power of whatever number loop it's on:

After finding the sum for each of these linked lists, my idea was to add them together and then convert that to a string and then go from front to back. This is my initial submission which also passed 1566/1569:

func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
    curr := l1
    power := 0.0
    outputl1, outputl2   := 0, 0
    for curr != nil {
        multiplier := math.Pow(10.0, power) 
        sum := curr.Val * int(multiplier)
        outputl1 += sum
        curr = curr.Next
        power += 1.0
    }
    curr = l2
    power = 0.0
    for curr != nil {
        multiplier := math.Pow(10.0, power) 
        sum := curr.Val * int(multiplier)
        outputl2 += sum
        curr = curr.Next
        power += 1.0
    }

    sum := outputl1 + outputl2
    sumStr := strconv.Itoa(sum)
    
    var head *ListNode
    for i := 0; i < len(sumStr); i++ {
        val := int(sumStr[i] - '0')
        node := &ListNode{Val: val, Next: head}
        head = node
    }

    return head
}

I tried debugging why the following test case was failing:

Input:

l1 = [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]

l2 = [5,6,4]

Eventually I gave up and looked at the leetcode discussion only to realize this is a common issue related to the max size of ints. So I decided to simply extract some of the code, clean up the logic, and leave it at that, hence the final submission.

Go Solution
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
	sum1, sum2 := getSumFromList(l1), getSumFromList(l2)
	sum := sum1 + sum2

	return createListFromSum(sum)
}

func createListFromSum(sum int) *ListNode {
    if sum == 0 {
        return &ListNode{Val: 0}
    }

    dummy := &ListNode{}
    current := dummy

    for sum > 0 {
        val := sum % 10
        current.Next = &ListNode{Val: val}
        current = current.Next
        sum /= 10
    }

    return dummy.Next
}

func getSumFromList(currentNode *ListNode) int {
	power := 0.0
	sum := 0
	for currentNode != nil {
		multiplier := math.Pow(10.0, power)
		localSum := currentNode.Val * int(multiplier)
		sum += localSum
		currentNode = currentNode.Next
		power += 1.0
	}

	return sum
}
LeetCode Problem Link