给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。
- 示例 1:
输入: 123
输出: 321
- 示例 2:
输入: -123
输出: -321
- 示例 3:
输入: 120
输出: 21
- 注意:
假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [−231, 231 − 1]。请根据这个假设,如果反转后整数溢出那么就返回 0。
class Solution {
public:int reverse(int x) {int max = (1<<31)-1;int min = (1<<31);int numbers[10];bool label = true;if (x < 0) {label = false;if (x != min) {x = -x;} else {return 0;}} if (x == 0) {return 0;}int count = 0;while (x > 0) {int tmp = x % 10;x /= 10;numbers[count++] = tmp;}long result = 0;for (int i = 0; i < count; i++) {result = result * 10 + numbers[i];}if (result > max) {return 0;}if (!label) {return -result;} else {return result;}}
};
or
class Solution {
public:int reverse(int x) {bool negative = false;if (x < 0) {negative = true;if (x == INT_MIN) {return 0;} else {x = -x;}}long result = 0;while (x > 0) {result = result * 10 + x%10;x/=10;}if (result > INT_MAX) {return 0;} else if (negative){return -result;} else {return result;}}
};
or
class Solution {
public:int reverse(int x) {long result = 0;while (x != 0) {result = result * 10 + x%10;x/=10;}if (result > INT_MAX || result < INT_MIN) {return 0;} else {return result;}}
};
注:
INT_MIN 和 INT_MAX,均定义在 <limits.h>头文件中#define INT_MAX 2147483647
#define INT_MIN (-INT_MAX - 1)
来源:力扣(LeetCode)