Problem
Given a signed 32-bit integer x
, return x
with its digits reversed. If reversing x
causes the value to go outside the signed 32-bit integer range [-2^31, 2^31 - 1]
, then return 0
.
Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
Examples
Example1:
|
|
Example2:
|
|
Solution
Method 1 - Convert Number to String and Reverse
We can convert the integer to a string/char array, reverse the order, and convert the string/char array back to an integer. However, this will require extra space for the string. It doesn’t seem to be the right way, if you come with such a solution.
❌ Problem - 64 Bit integer not allowed
Method 2 - Using Mod and Divide
For Reversing the integer, we can use mod operator to extract the digit and reverse it by multiplying by 10.
For eg. 123
|
|
Here is the code:
|
|
❌ Problem - Will not handle overflow
Handling Integer Out of Bound Case
We can use 64bit integer to store reverse.
|
|
❌ Problem - 64 Bit integer not allowed
Handling Integer Out of Bound without 64 Bit Integers 🏆
Now this becomes challenging, we have to pre-empt adding digit to reversed number. Before adding check if we are overflowing. We know integer min value = -2147483648 and max value = 2147483647.
Here is the code:
|
|