Algorithm
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 [-231, 231 - 1]
, then return 0
.
Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
Example 1:
Input: x = 123 Output: 321
Example 2:
Input: x = -123 Output: -321
Example 3:
Input: x = 120 Output: 21
Constraints:
-231 <= x <= 231 - 1
Code Examples
#1 Code Example with Javascript Programming
Code -
Javascript Programming
var reverse = function(x) {
let rev = 0;
let rem;
let isNegative = x < 0;
if (isNegative)
x = (-1) * x;
while(x != 0 ) {
rem = x % 10;
x = parseInt(x / 10);
rev = parseInt(rev + '' + rem);
}
if (rev > 0x7FFFFFFF)
return 0;
if (isNegative)
return (-1) * rev;
return rev;
};
Copy The Code &
Try With Live Editor
Input
Output
#2 Code Example with C Programming
Code -
C Programming
int reverse(int x) {
int d, k = 0;
while (x) {
d = x % 10;
if ((x > 0 && k > (0x7fffffff - d) / 10) ||
(x < 0 && k < ((signed)0x80000000 - d) / 10)) {
return 0;
}
k = k * 10 + d;
x = x / 10;
}
return k;
}
Copy The Code &
Try With Live Editor
Input
Output
#3 Code Example with C++ Programming
Code -
C++ Programming
class Solution {
public:
int reverse(int x) {
string s = to_string(x);
int base = 1;
int i = s[0] == '-' ? 1 : 0;
int res = 0;
while(i < s.size()){
if(base == 1000000000 && (s[i] - '0' > 2 || INT_MAX - (s[i] - '0') * base < res)) return 0;
res += (s[i] - '0'> * base;
base *= 10;
i++;
}
return s[0] == '-' ? -res : res;
}
};
Copy The Code &
Try With Live Editor
Input
Output
#4 Code Example with C# Programming
Code -
C# Programming
namespace LeetCode
{
public class _007_ReverseInteger
{
public int Reverse(int x)
{
var result = 0;
var positiveOverflow = int.MaxValue / 10;
var nagativeOverflow = int.MinValue / 10;
for (; x != 0; x /= 10)
{
if (result > positiveOverflow || result < nagativeOverflow)
{
return 0;
}
result = result * 10 + x % 10;
}
return result;
}
}
}
Copy The Code &
Try With Live Editor
Input
Output
#5 Code Example with Java Programming
Code -
Java Programming
class Solution {
public int reverse(int x) {
int reverse = 0;
while (x != 0) {
int rem = x % 10;
x /= 10;
if (reverse > Integer.MAX_VALUE / 10 || (reverse == Integer.MAX_VALUE / 10 && rem > 7)) {
return 0;
}
if (reverse < Integer.MIN_VALUE / 10 || (reverse == Integer.MIN_VALUE / 10 && rem < -8)) {
return 0;
}
reverse = reverse * 10 + rem;
}
return reverse;
}
}
Copy The Code &
Try With Live Editor
Input
Output
#6 Code Example with Python Programming
Code -
Python Programming
class Solution:
def reverse(self, x):
x = int(str(x)[::-1]) if x >= 0 else int("-" + str(x)[::-1][:-1]); return -2 ** 31 <= x <= 2 ** 31 - 1 and x or 0
Copy The Code &
Try With Live Editor
Input
Output
Demonstration
Leetcode - Reverse Integer Solution in Javascript