Problem
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.
Solution
fun reverse(x: Int): Int {
val str = x.toString()
val stack = Stack<Char>()
var result = ""
str.forEach {
stack.push(it)
}
while (true) {
if (stack.size == 0) break
if (result.isEmpty() && stack.peek() == '0') {
if (stack.size == 1) {
result = "0"
break
}
stack.pop()
continue
}
if (stack.peek() == '-') {
result = stack.peek() + result
break
}
result += stack.pop()
}
return try {
result.toInt()
} catch (e: NumberFormatException) {
0
}
}
fun reverse(x: Int): Int {
val output = StringBuilder()
var currVal = x
if (currVal < 0) {
currVal *= -1
output.append("-")
}
output.append(currVal.toString().reversed())
return output.toString().toIntOrNull() ?: 0
}
fun reverse(x: Int): Int {
val y = abs(x)
.toString()
.reversed()
.toIntOrNull() ?: return 0
return when {
0 <= x -> y
else -> y * -1
}
}
Test code
@Test
fun reverse() {
assertEquals(321, solution.reverse(123))
assertEquals(-321, solution.reverse(-123))
assertEquals(21, solution.reverse(120))
assertEquals(21, solution.reverse(1200))
assertEquals(0, solution.reverse(0))
assertEquals(0, solution.reverse(1534236469))
}
Model solution
https://leetcode.com/problems/reverse-integer/solution/
Approach 1: Pop and Push Digits & Check before Overflow
class Solution {
public int reverse(int x) {
int rev = 0;
while (x != 0) {
int pop = x % 10;
x /= 10;
if (rev > Integer.MAX_VALUE/10 || (rev == Integer.MAX_VALUE / 10 && pop > 7)) return 0;
if (rev < Integer.MIN_VALUE/10 || (rev == Integer.MIN_VALUE / 10 && pop < -8)) return 0;
rev = rev * 10 + pop;
}
return rev;
}
}
Top comments (0)