class Solution {
public:
int reverse(int x) {
int ans = 0;
while (x) {
int temp = ans * 10 + x % 10;
if (temp / 10 != ans)
return 0;
ans = temp;
x /= 10;
}
return ans;
}
};
8 ms simple C++ solution which checks overflow

@Aeonaxx said in 8 ms simple C++ solution which checks overflow:
8 ms solution
Lies. It takes 35 milliseconds.

@kirkdokuzelli Yes. I saw they must have updated test cases. Then the solution one year ago couldn't remain 8ms. Does it make sense? LOL :)

@Aeonaxx said in 8 ms simple C++ solution which checks overflow:
@kirkdokuzelli Yes. I saw they must have updated test cases. Then the solution one year ago couldn't remain 8ms. Does it make sense? LOL :)
While the fact that this works is awesome, it's performance is among the worst. No offense.

@kirkdokuzelli
I tried using 8 bytes long integer solution but can only get 15 ms runtime.class Solution { public: int reverse(int x) { long long ans = 0; while (x) { ans = ans * 10 + x % 10; x /= 10; } return ans < INT_MIN  ans > INT_MAX ? 0 : ans; } };
I think maybe most of the low runtime solutions were submitted a year ago.
Another of my solution is just a little better. I post it here FYI.
class Solution { public: int reverse(int x) { int ans = 0, lo = INT_MIN / 10, hi = INT_MAX / 10; while (x) { if (ans < lo  ans > hi) return 0; int r = x % 10; ans = ans * 10; if (r < 0 && ans < INT_MIN  r  r > 0 && ans > INT_MAX  r) return 0; ans += r; x /= 10; } return ans; } };

@Aeonaxx
INT_MIN
andINT_MAX
is the old C style way. In C++, it's better to usestd::numeric_limits<int>::min()
andstd::numeric_limits<int>::max()



@Aeonaxx interesting... because if you open a python console and try 3 % 10, it's 7. I even Googled it and 3 % 10 = 7 lol. How did you check it on your machine?

@rosita It looks python is different for mod. I tested in C++ (Xcode) and Java (IntelliJ).

@bianlu because that sentence /* if (temp / 10 != ans) return 0; */
if temp overflows, temp / 10 != ans, and it will return 0