LeetCode No.7 Reverse Integer |
2016-11-02 本文已影响0人
wxqyppqm
Q:
Reverse digits of an integer.
Example1: x = 123, return 321Example2: x = -123, return -321
- If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.
- Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?
- For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
A:
public class Solution {
public int reverse(int x) {
long result =0; //为了处理Integer的边界值,这里初始化成long
while(x != 0)
{ //之前的结果乘以10(在前,前一位),后来的值是module 10求模得到的(在后,后一位)
result = (result*10) + (x%10);
if(result > Integer.MAX_VALUE) return 0;
if(result < Integer.MIN_VALUE) return 0;
x = x/10; //处理下一位,从右至左
}
return (int)result;
}
}
test case: 939
- result = 0*10 + 939%10 = 0 + 9 = 9
x = 939/10 = 93 - result = 9*10 + 93%10 = 90 + 3 = 93
x = 93/10 = 9 - result = 93*10 + 9%10 = 939
x = 9/10 = 0 (结束)
test case: -100
- result = 0*10 + (-100)%10 = 0 + 0 = 0
x = (-100)/10 = (-10) - result = 0*10 + (-10)%10 = 0 + 0 = 0
x = (-10)/10 = -1 - result = 0*10 + (-1)%10 = 0 + (-1) = -1
x = -1/10 = 0 (结束)
Notes:
关于module取模
(-10)/3 = -3
10/(-3) = -3
(-10)/(-3) = 3
(-10)%3 = -1
10%(-3) = 1
(-10)%(-3) = -1
5%3 = 2
-5%3 = -2
5%-3 = 2
-5%-3 = -2 //结果符号由之前的那个数字来决定
5.3%3 = 2.3
5%3.3 = 1.7000000000000002 //取模支持小数
5.3%3.3 = 2.0 //两个小数也可以取模