Skip to content

Instantly share code, notes, and snippets.

@wcang
Last active April 23, 2022 13:52
Show Gist options
  • Select an option

  • Save wcang/43d975f06631ac38f2355a75d28ecf68 to your computer and use it in GitHub Desktop.

Select an option

Save wcang/43d975f06631ac38f2355a75d28ecf68 to your computer and use it in GitHub Desktop.
Add Two Numbers. Problem is described here: https://leetcode.com/problems/add-two-numbers/
import org.junit.jupiter.api.Named.of
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.Arguments
import org.junit.jupiter.params.provider.Arguments.arguments
import org.junit.jupiter.params.provider.MethodSource
import java.util.stream.Stream
import kotlin.test.assertEquals
internal class AdderKtTest {
@ParameterizedTest
@MethodSource("testCases")
fun testAdd(left: List<Int>, right: List<Int>, expected: List<Int>) {
assertEquals(expected, add(left, right))
}
companion object {
@JvmStatic
private fun testCases(): Stream<Arguments> {
return Stream.of(
arguments(emptyList<Int>(), emptyList<Int>(),
of("Expect empty list when both left and right are empty", emptyList<Int>())),
arguments(listOf(1), listOf(9),
of("Both list with single element with carry", listOf(1, 0))),
arguments(listOf(1), listOf(8),
of("Both list with single element without carry", listOf(9))),
arguments(listOf(0, 1), listOf(8),
of("Test list with preceeding zeroes", listOf(9))),
arguments(listOf(9, 8, 7), listOf(2, 3),
of("Test left > right elements with carry at the end", listOf(1, 0, 1, 0))),
arguments(listOf(4, 5), listOf(7, 1, 2, 3),
of("Test left < right elements without carry", listOf(7, 1, 6, 8))),
arguments(listOf(8, 8, 4, 8, 3, 9), listOf(0, 2, 5, 2, 2, 2),
of("Test with interspersed carries", listOf(9, 1, 0, 0, 6, 1))),
)
}
}
}
import kotlin.math.max
fun add(left: List<Int>, right: List<Int>) : List<Int> {
val l = left.asReversed()
val r = right.asReversed()
val result = mutableListOf<Int>()
val max = max(l.size, r.size)
var carry = 0
repeat(max) {
val num1 = l.getOrElse(it) { 0 }
val num2 = r.getOrElse(it) { 0 }
val sum = num1 + num2 + carry
result.add(sum % 10)
carry = sum / 10
}
if (carry != 0)
result.add(carry)
return result.reversed().dropWhile { it == 0 }
}
@wcang
Copy link
Author

wcang commented Apr 23, 2022

Implementation of adder and test suite to exercise what I learned from Effective Software Testing Chapter 2.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment