Reverse digits of an integer.
Example1: x = 123, return 321 Example2: x = -123, return -321
Have you thought about this? 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
大意: 題目要求將一個數反轉,如123反轉為321,但是有一點需要注意,要考慮溢出,32位的Integer范圍是:-2147483646 ~ 2147483646 1. 假如一開始就傳入大于或小于這個范圍的值,要怎么處理 2. 如果反轉后的值大于或小于這個范圍的值,要怎么處理
我的思路是: 首先把int值強轉為long來計算,然后在while內,從個位開始反轉
我的代碼:
public class Solution { public int reverse(int x) { int flag = 1; long nx = (long) x; if(nx < 0){ flag = -1; nx = -nx; } if(nx > Integer.MAX_VALUE){ return 0; } if(nx < 10){ return x; } long sum = 0; //反轉 while(nx != 0){ sum = sum*10 + nx%10; nx /= 10; } if(sum > Integer.MAX_VALUE){ return 0; } return ((int)sum * flag); }}Discussion的優秀代碼: 它的高明之處是:在反轉的每一步計算過程中,判斷當前的sum是否溢出,然后做處理; 而我的做法是,在開始和結束處處理溢出,所以代碼沒那么簡潔
public class P7 { public int reverse(int x) { long rev= 0; while( x != 0){ rev= rev*10 + x % 10; x= x/10; if( rev > Integer.MAX_VALUE || rev < Integer.MIN_VALUE) return 0; } return (int) rev; }}新聞熱點
疑難解答