Invert values in Kotlin

The challenge

Given a set of numbers, return the additive inverse of each. Each positive becomes negatives, and the negatives become positives.

invert([1,2,3,4,5]) == [-1,-2,-3,-4,-5] invert([1,-2,3,-4,5]) == [-1,2,-3,4,-5] invert([]) == []

The solution in Kotlin code

Option 1:

fun invert(arr: IntArray) = arr.map { -it }.toIntArray()
Code language: Kotlin (kotlin)

Option 2:

fun invert(arr: IntArray): IntArray { return IntArray(arr.size){ -arr[it] } }
Code language: Kotlin (kotlin)

Option 3:

fun invert(arr: IntArray): IntArray { var x = 0 while (x < arr.size) { arr[x] = arr[x] * -1 x++ } return arr }
Code language: Kotlin (kotlin)

Test cases to validate our solution

import org.junit.Assert.*; import org.junit.Test class TestExample { @Test fun testFixed() { assertArrayEquals(intArrayOf(-1,-2,-3,-4,-5), invert(intArrayOf(1,2,3,4,5))) assertArrayEquals(intArrayOf(-1,2,-3,4,-5), invert(intArrayOf(1,-2,3,-4,5))) assertArrayEquals(intArrayOf(), invert(intArrayOf())) assertArrayEquals(intArrayOf(0), invert(intArrayOf(0))) } }
Code language: Kotlin (kotlin)
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments