Solution:
class Solution {
public:
int reverse(int x) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int sol = 0;
while (x) {
sol = sol * 10 + x % 10;
x = x / 10;
}
return sol;
}
};
// Operator preserve the sign.
==== Correct one =====
class Solution {
public:
int reverse(int x) {
int sign = 1;
if (x < 0) {
sign = -1;
}
x = abs(x);
int ans = 0;
while (x > 0) {
if (ans > INT_MAX/10) {
return 0;
}
ans *= 10;
ans += x % 10;
x = x / 10;
}
return ans * sign;
}
};
class Solution {
public:
int reverse(int x) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int sol = 0;
while (x) {
sol = sol * 10 + x % 10;
x = x / 10;
}
return sol;
}
};
// Operator preserve the sign.
==== Correct one =====
class Solution {
public:
int reverse(int x) {
int sign = 1;
if (x < 0) {
sign = -1;
}
x = abs(x);
int ans = 0;
while (x > 0) {
if (ans > INT_MAX/10) {
return 0;
}
ans *= 10;
ans += x % 10;
x = x / 10;
}
return ans * sign;
}
};
No comments:
Post a Comment