LeetCode problem No.7.
No.6 is here.
7. Reverse Integer
https://leetcode.com/problems/reverse-integer/
Given a 32-bit signed integer, reverse digits of an integer.
Example 1
Input: 123 Output: 321
Example 2
Input: -123 Output: -321
Example 3
Input: 120 Output: 21
Note Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
Code 1
object Solution { def reverse(x: Int): Int = { var tmp = x var result = 0L while(tmp/10 != 0) { val digit = tmp%10 result = result * 10 + digit tmp = tmp/10 } result = result * 10 + tmp if(result < scala.Int.MinValue || result > scala.Int.MaxValue) 0 else result.toInt } }
Methods
- Divide x by 10 and get remainder.
- Multiply current result by 10 and add remainder.
- When x becomes smaller than 10, exit while.
- If result is not in the the 32-bit signed integer range, result is 0.
Result
Runtime: 724 ms, faster than 5.95% of Scala online submissions for Reverse Integer. Memory Usage: 54.2 MB, less than 100.00% of Scala online submissions for Reverse Integer.
Very slowly...orz
Code 2
object Solution { def reverse(x: Int): Int = { var tmp = x var result = 0L Iterator.continually(tmp).takeWhile( n => n/10 != 0).foreach { n => val digit = n%10 result = result * 10 + digit tmp = tmp/10 } result = result * 10 + tmp if(result < scala.Int.MinValue || result > scala.Int.MaxValue) 0 else result.toInt } }
Methods
- Use
Iterator.continually
instead ofwhile
Result
Runtime: 428 ms, faster than 5.95% of Scala online submissions for Reverse Integer. Memory Usage: 54.2 MB, less than 100.00% of Scala online submissions for Reverse Integer.
A little bit optimized, but not fast yet.
Code 3
object Solution { def reverse(x: Int): Int = { val result = if(x >= 0) x.toString.reverse.toLong else x.toString.reverse.init.toLong * -1 if(result < scala.Int.MinValue || result > scala.Int.MaxValue) 0 else result.toInt } }
Methods
- Convert Int to String
- Reverse String
- Convert String to Long
- If result is not in the the 32-bit signed integer range, result is 0.
Result
Runtime: 616 ms, faster than 5.95% of Scala online submissions for Reverse Integer. Memory Usage: 54.1 MB, less than 100.00% of Scala online submissions for Reverse Integer.
⛳!!