LeetCode

LeetCode -- Reverse Integer

2016-05-25  本文已影响4人  zsliger

[问题:]

Reverse digits of an integer.

Example1:x = 123, return 321

Example2:x = -123, return -321

题解:给定一个整数,将这个整数的数字旋转位置。

分析:

注意点1:如果一个整数最后一位位0,比如:10100,那么反转后将变成101。

注意点2:如果输入的数为1000000003,那么反转后将会出现溢出,需要注意。

解法:

public intreverse(intx) {

intresult =0;

while(x !=0) {

result = result *10+ x %10;// 每一次都在原来结果的基础上变大10倍,再加上余数

x = x /10;// 对x不停除10

}

if(result < Integer.MIN_VALUE|| x > Integer.MAX_VALUE) {

return0;

}else{

returnresult;

}

}

上一篇 下一篇

猜你喜欢

热点阅读