题目:Reverse Integer
给定一个带符号的int类型数值,编写一个程序,使数的数字部分顺序反转,并输出。
注意:要注意int类型的数值取值范围,防止反转过后数值溢出。
思路:使输入的数值x对10取模,即x%10,得到个位数,然后对10取商,得到10的整数倍数,随之求得每步反转的数值,以此循环。
代码:
package cn.edu.www;
class TestDemo{
public static void main(String args[]){
System.out.println(new Solution().reverse(-560));
}
}
class Solution {
public int reverse(int x) {
int rev = 0;
while (x != 0) {
int pop = x % 10;//pop=个位数字
x /= 10;
/*以下是考虑两种int型溢出的情况
Integer.MAX_VALUE=2147483647,Integer.MIN_VALUE=-2147483648
当反转后的值超出int型范围时,就返回0 */
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;
}
}
运行结果:
-65