7. Reverse Integer
程序员文章站
2022-07-15 14:39:23
...
Reverse Integer
Easy
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
solution
class Solution {
public int reverse(int x) {
if(x == 0 || x >= Integer.MAX_VALUE || x <= Integer.MIN_VALUE)//刚开始也要判断
return 0;
int ret = 0;
int y = Math.abs(x);
while(y > 0){
int d = y % 10;
if(ret > Integer.MAX_VALUE/10 || (ret== Integer.MAX_VALUE/10 && d > 7) )
return 0;//在中间的push过程中可能会overflow Integer的最大值2147483647
if (ret < Integer.MIN_VALUE/10 || (ret == Integer.MIN_VALUE / 10 && d < -8))
return 0;//Integer的最小值-2147483648
ret = ret * 10 + d;
y = y / 10;
}
if(x < 0)
ret = -ret;
return ret;
}
}
32bit也就是4个字节,也就是int类型的取值范围
Algorithm
上一篇: 7. Reverse Integer
下一篇: 7. Reverse Integer
推荐阅读
-
Leetcode解题 7. Reverse Integer 反转整数
-
关于tf.reverse_sequence()简述
-
Mybatis Integer类型参数值为0时得到为空的解决方法
-
Reverse a String-freecodecamp算法题目
-
PHP中的integer类型使用分析
-
[springboot 开发单体web shop] 7. 多种形式提供商品列表
-
Python 列表排序方法reverse、sort、sorted详解
-
解决出现Incorrect integer value: '' for column 'id' at row 1的问题
-
JAVA Integer类型自加实例详解
-
Java中Integer.parseInt和Integer.valueOf,你还傻傻分不清吗?