标签:sed -- 参考 minus 解法 保留 only 要求 when
Hello 各位,这里是新治的第二篇博客,今天要解的这道题是LeetCode第七题,整数反转,先来读一下题:
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.
给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。
示例 1:
输入: 123
输出: 321
示例 2:
输入: -123
输出: -321
示例 3:
输入: 120
输出: 21
注意:
假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [−231, 231 − 1]。请根据这个假设,如果反转后整数溢出那么就返回 0。
先来说一下我个人解体的思路吧。
1. 首先要确定这个数的位数, 于是新建一个 n 用于记录;由于接下来还要对 x 进行操作,因此新建一个 y 令其等于 x,可以看作是备份一个原数。
计算位数的方法:对 x 的绝对值进行除以10 的操作,直到 x 变成0为止,每除一次就进行一次n++。
2. 接下来新建两个整型数 t 和 ans,并且再写一个 for 循环;在这个循环中, y 用于进行除以十的操作, 然后将得到的数赋值给 t,再将得到的 t 值赋值给 ans 并使其放置在其应该在的位数。
3. 最后进行溢出判定,也就是 int 类型的边界。
java代码如下:
classSolution {public int reverse(intx) {//n 求位数,y 用于保留 x 被操作前的值
int n = 0, y =x;for(int i = 1; Math.abs(x) > 0; i++){
x= x / 10;
n+= 1;
}//t 用于求每一位上的数字,ans用于记录答案
int t = 0, ans = 0;for(int i = n ; i > 0; i--){
t= y % 10;
y= y / 10;
ans+= t * Math.pow(10, i - 1);
}//这里进行值的判定,符合题目要求的值就正常返回,不符合的就返回0。
if (ans > Math.pow(2, 31)-2 || ans ){
return 0;
}else{returnans;
}
}
}
这里再讲一点,也是我自己做题的时候遇到的一个错误:
有的数,它作为 input 是没有问题的(在 int 类型的范围中),但是其反转之后是不在范围内的,比如说下面两个 input:
“1534236469” 和 “-1563847412”; 他们的反转分别是 "9646324351" 和 “-2147483651”,这两个都是需要我们返回 0 的输入,记得不能搞错。
希望有所帮助,感谢。
参考资料:
https://leetcode.com/problems/reverse-integer/
https://leetcode-cn.com/problems/reverse-integer/
【LeetCode 力扣】7. Reverse Integer 整数反转 Java 解法
标签:sed -- 参考 minus 解法 保留 only 要求 when