Kotlin Algorithm Challenge No. 3
Tags: kotlin, algorithms
Published: 2020-01-22 18:13:40

Originally posted [here](http://bit.ly/37jB0v8)

The following problem is the [Reverse Integer](https://leetcode.com/problems/reverse-integer/) problem on LeetCode.

# Problem

Given a 32-bit signed integer, reverse its digits.

```kotlin
fun reverse(x: Int): Int {
    // TODO
}
```
<br />
<br />
<br />

# Solution

This problem is not too difficult (i.e. this is absolutely a fair interview question!). The approach we're going to take is **breaking down the number by multiples of 10, and using the broken off piece to construct the reversed number**.

There might be a temptation to convert the value to a string, reverse it, then convert it back again. Don’t do that, it's completely against the spirit of the problem. I also trust math more than I trust type conversion, if code like this were to ever make it into production.

```kotlin
fun reverse(x: Int): Int {
    var int = x
    var sum = 0

    while (int != 0) {
        val digit = (int % 10)

        val newSum = 10*sum.toLong() + digit.toLong()
        check(newSum > Integer.MIN_VALUE && newSum < Integer.MAX_VALUE) {
            "Integer overflowed, input too large"
        }

        sum = newSum.toInt()
        int /= 10
    }

    return sum
}
```
<br />

You can see the progression of our `sum` variable in the following example.

```kotlin
1234

10*0 + 4 = 4
10*4 + 3 = 43
10*43 + 2 = 432
10*432 + 1 = 4321
```
<br />
<br />

# Writing Good Kotlin Code

But how does idiomatic Kotlin code fit into this problem?
<br />

## Pure Functions

A pure function is a function that doesn't mutate it's input, and it has no side effects. Because of these two things, when a pure function is run multiple times with the same input, it gives the same result.

It's not obvious in the above code, but Kotlin is making me go out of my way to write a pure function. Try the following:

```kotlin
fun foo(x: Int) {
    x = 4  // an error pops up: "Val cannot be reassigned"
}
```
<br />

In a similar vein, collections are immutable by default.

```kotlin
fun foo(list: List<Int>) {
    list.add(4) // nope! the compiler won't allow it!
}
```
<br />

The above isn't allowed, because the `List` interface extends the `Collection` interface, *which doesn't contain an `add` method*. If you want an add method, you have to declare `MutableList`, which extends `MutableCollection`. And putting `MutableList` as a type of a function input parameter should set off a red flag in your head.
<br />

## Check

The `check` function checks some condition. If it is `false`, it throws an `IllegalStateException`. We can use it to make sure people are only calling our function at the right time.

Similar to `check` is the function `require`. We pass it a condition, and if `false`, it throws an `IllegalArgumentException`. So it is used for validating input. e.g.

```kotlin
fun poundsToKilograms(weightInPounds: Double) {
    require(weightInPounds >= 0) {
        "There's no such thing as a negative weight."
    }
     
    return weightInPounds / 2.2
}
```
<br />
<br />
<br />

## Augmented Assignment Operators

The slightly funny looking operator `/=` means divide and then assign. That line is equivalent to the following.

```kotlin
int = int / 10
```
<br />
<br />
<br />

# Summary

Thank you for reading the most recent Kotlin Algorithm Challenge! If you want to learn more about Kotlin, you can see all the articles I’ve written about it [here](https://www.alexhwoods.com/kotlin/).