# Shortest code possible in c++

• long long make res a 64 bit number, the overflow is checked.

``````class Solution {
public:
int reverse(int x) {
long long res = 0;
while(x) {
res = res*10 + x%10;
x /= 10;
}
return (res<INT_MIN || res>INT_MAX) ? 0 : res;
}
};``````

• This post is deleted!

• My algorithm is same to you,but retun TLE,only due python?

• My method was similar, but with an overflow check in the loop before multiplying. I considered the long method, but felt that it would be slightly less defensible in an interview even though it is faster.

• you are using long long, a larger storage unit than int

• oh! That is really short !

• ``````class Solution {
public:
int reverse(int x) {
long long j = 0;
do{
j = j * 10 + x % 10;
}while (x /= 10);
return (j > INT_MAX || j < INT_MIN) ? 0: (int)j;
}
};
``````

hahahahaha

• what if the input is 64 bits integer ?

• you should judge first, as long as input is overflow, return 0;

• ``````    long long res = x % 10;
while(x /= 10) res = res*10 + x%10;
return (res<INT_MIN || res>INT_MAX) ? 0 : res;``````

• ``````int reverse(int x, long r=0) {
return x ? reverse(x/10, r*10 + x%10) : (int(r) == r) * r;
}
``````

or

``````int reverse(int x) {
long r = 0;
while (x) r = r*10 + x%10, x /= 10;
return (int(r) == r) * r;
}``````

• @StefanPochmann

usually,
long is 32bit on windows, and 64bit on unix.
while long long is always 64bit.

https://en.wikipedia.org/wiki/Integer_(computer_science)

• @forsaken I know. And I know what it is on LeetCode :-)

Now tell me that `int(r)` is undefined if `r` is outside of `int` range :-P

• @StefanPochmann
it is implementation-deﬁned.

• @EvanPerlinHu, if its `long long`, then we check for overflow possibility before each operation so as not to invoke Undefined Behavior. (Though there is a faster way if we are going to rely on Undefined Behavior: recall that signed integer overflow in C++ is Undefined Behavior).

``````const auto Max = std::numeric_limits<long long>::max();
long long Ans = 0;
while(x != 0){
auto mod = x % 10;
if(Max / 10 < Ans)  //Will it overflow if we do Ans *=10 ?
return 0;
Ans *= 10;
if(Max - mod < Ans)  //Will it overflow if weadd mod to Ans ?
return 0;
Ans += mod;
x /= 10;
}
``````

Of cause, we assume `x` is a positive integer, though we could always take out the sign before doing this operation and bring it back later

• ...
std::string num = std::to_string(x);
num[0] == '-' ? std::reverse(num.begin() + 1, num.end()) : std::reverse(num.begin(), num.end());
return (std::stoll(num)>INT32_MAX||std::stoll(num)<INT32_MIN)? 0:std::stoll(num);
...
Is shorter.

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.