LEETCODE 7. Reverse Integer 判斷溢位的解決方案
題目:
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!
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.
要求能判斷溢位,若溢位則返回0。
網上的大部分解法是用更長的long型來判斷是否超過了int的32位來判斷溢位。網上的第二種解法是用String型別來判斷,本質還是用了更長的資料型別。
但是這樣質保不治本,因為如果題目要求翻轉一個64位的long型變數,則沒有更大的資料型別(或者永遠都可以要求翻轉最大的資料型別)。
我的方法是在最後一次“乘以10然後加餘數”之前,判斷這個值是否接下來會溢位,核心程式碼如下:
public int reverse(int n) { int initiall = n; int result = 0; int count = 0; for (int ii = 0; initiall != 0; count++) { initiall = initiall / 10; } for (int i = 0; i < count; i++) { if (i == count - 1) { if (result > Integer.MAX_VALUE / 10 || ((result == Integer.MAX_VALUE / 10) && (n % 10 > Integer.MAX_VALUE % 10))) { result = 0; break; } if (result < Integer.MIN_VALUE / 10 || ((result == Integer.MIN_VALUE / 10) && (n % 10 < Integer.MIN_VALUE % 10))) { result = 0; break; } } result = result * 10 + n % 10; n = n / 10; } return result; }