(...as I still learning Kotlin) I found this "problem":
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
This is my solution so far:
fun add(a: IntArray, b: IntArray): Iterable<Int> {
val result: MutableList<Int> = mutableListOf()
var remainder = 0
for (i in 0..Math.max(a.size, b.size) - 1) {
val sum = a.elementAtOrElse(i, { 0 }) + b.elementAtOrElse(i, { 0 }) + remainder
remainder = if (sum >= 10) 1 else 0
result.add(if (remainder >= 1) sum - 10 else sum)
}
if (remainder > 0) result.add(remainder)
return result
}
...test cases:
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
class AddTwoNumbersTest {
@Test
fun test_Add() {
assertThat(add(intArrayOf(9, 6, 9, 5, 9), intArrayOf(1, 5, 1, 6, 1))).isEqualTo(listOf(0, 2, 1, 2, 1, 1))
assertThat(add(intArrayOf(4, 1, 8, 7, 2), intArrayOf(9, 4, 1, 0, 3))).isEqualTo(listOf(3, 6, 9, 7, 5))
assertThat(add(intArrayOf(2, 2, 3, 3), intArrayOf(4, 5, 6, 7))).isEqualTo(listOf(6, 7, 9, 0, 1))
assertThat(add(intArrayOf(4, 1, 0, 8), intArrayOf(2, 2, 7, 6))).isEqualTo(listOf(6, 3, 7, 4, 1))
assertThat(add(intArrayOf(2, 7, 1, 0), intArrayOf(0, 0, 8, 1))).isEqualTo(listOf(2, 7, 9, 1))
assertThat(add(intArrayOf(9, 9, 9), intArrayOf(9, 9, 9))).isEqualTo(listOf(8, 9, 9, 1))
assertThat(add(intArrayOf(9, 3, 7), intArrayOf(8, 7, 8))).isEqualTo(listOf(7, 1, 6, 1))
assertThat(add(intArrayOf(6, 6, 6), intArrayOf(7, 8, 9))).isEqualTo(listOf(3, 5, 6, 1))
assertThat(add(intArrayOf(0, 0, 0), intArrayOf(0, 0, 0))).isEqualTo(listOf(0, 0, 0))
assertThat(add(intArrayOf(2, 4, 3), intArrayOf(5, 6, 4))).isEqualTo(listOf(7, 0, 8))
assertThat(add(intArrayOf(0, 1), intArrayOf(0, 1, 2))).isEqualTo(listOf(0, 2, 2))
assertThat(add(intArrayOf(4, 6), intArrayOf(6, 4))).isEqualTo(listOf(0, 1, 1))
assertThat(add(intArrayOf(1), intArrayOf(9, 9))).isEqualTo(listOf(0, 0, 1))
assertThat(add(intArrayOf(), intArrayOf(0, 1))).isEqualTo(listOf(0, 1))
assertThat(add(intArrayOf(), intArrayOf())).isEmpty()
}
}
It works so far...so I'm wondering if you can improve this one, or have a better approach. Notice I use everything the language offer.