Kotlin Algorithm Challenge #3
The following problem is the Reverse Integer problem on LeetCode.
Problem
Given a 32-bit signed integer, reverse its digits.
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.
You can see the progression of our sum
variable in the following example.
Writing Good Kotlin Code
But how does idiomatic Kotlin code fit into this problem?
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:
In a similar vein, collections are immutable by default.
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.
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.
Augmented Assignment Operators
The slightly funny looking operator /=
means divide and then assign. That line is equivalent to the following.
Wow! You read the whole thing. People who make it this far sometimes
want to receive emails when I post something new.
I also have an RSS feed.