Reverse Integer

Another super easy problem using math operations. The problem asks us to reverse the digits of an integer. For example, 123 should return 321. You should also maintain the original sign of the number whether it’s positive or negative. This problem took me about 3 minutes to solve.

class Solution {
    fun reverse(x: Int): Int {
        var positive = x >=0
        var n = Math.abs(x)        
        val builder = StringBuilder()
        
        while(n != 0){
            val a = n % 10
            n = n / 10
            builder.append(a)
        }
        
        return try{
            Integer.parseInt(builder.toString()) * if(positive) 1 else -1
        }catch(e: NumberFormatException){
            0
        }
    }
}
Runtime: 128 ms, faster than 93.88% of Kotlin online submissions for Reverse Integer.
Memory Usage: 31.5 MB, less than 100.00% of Kotlin online submissions for Reverse Integer.
comments powered by Disqus