整数翻转
This commit is contained in:
parent
dd71ac5ee5
commit
3e9e8f99c0
52
src/main/java/com/leetcode/string/ReverseNum.java
Normal file
52
src/main/java/com/leetcode/string/ReverseNum.java
Normal file
@ -0,0 +1,52 @@
|
||||
package com.leetcode.string;
|
||||
|
||||
/**
|
||||
*
|
||||
* 给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。
|
||||
|
||||
示例 1:
|
||||
|
||||
输入: 123
|
||||
输出: 321
|
||||
示例 2:
|
||||
|
||||
输入: -123
|
||||
输出: -321
|
||||
示例 3:
|
||||
|
||||
输入: 120
|
||||
输出: 21
|
||||
注意:
|
||||
|
||||
假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [−231, 231 − 1]。请根据这个假设,如果反转后整数溢出那么就返回 0。
|
||||
|
||||
来源:力扣(LeetCode)
|
||||
链接:https://leetcode-cn.com/problems/reverse-integer
|
||||
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
|
||||
*
|
||||
* @author zeek
|
||||
*
|
||||
*/
|
||||
public class ReverseNum {
|
||||
|
||||
public int reverse(int x) {
|
||||
int rev = 0;
|
||||
while (x != 0) {
|
||||
int pop = x % 10;
|
||||
x /= 10;
|
||||
if (rev > Integer.MAX_VALUE/10 || (rev == Integer.MAX_VALUE / 10 && pop > 7)) return 0;
|
||||
if (rev < Integer.MIN_VALUE/10 || (rev == Integer.MIN_VALUE / 10 && pop < -8)) return 0;
|
||||
rev = rev * 10 + pop;
|
||||
}
|
||||
return rev;
|
||||
}
|
||||
|
||||
|
||||
public static void main (String args[]) {
|
||||
ReverseNum reverse = new ReverseNum();
|
||||
Integer res = reverse.reverse(1534236469);
|
||||
System.out.println(res);
|
||||
}
|
||||
|
||||
|
||||
}
|
Loading…
Reference in New Issue
Block a user