题解 | #反转数字#
反转数字
https://www.nowcoder.com/practice/1a3de8b83d12437aa05694b90e02f47a
class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param x int整型 * @return int整型 */ int reverse(int x) { // write code here int reversedNum = 0; while (x != 0) { int digit = x % 10; // 检查反转后的数字是否超出了32位有符号整数的范围 if (reversedNum > INT_MAX / 10 || (reversedNum == INT_MAX / 10 && digit > 7)) { return 0; } if (reversedNum < INT_MIN / 10 || (reversedNum == INT_MIN / 10 && digit < -8)) { return 0; } reversedNum = reversedNum * 10 + digit; x /= 10; } return reversedNum; } };