標籤:style blog http ar io color os sp for
| 題目 |
Reverse Integer |
| 通過率 |
34.2% |
| 難度 |
Easy |
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
click to show spoilers.
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.
這是一個數字反轉的問題,翻轉的思想是將原數不斷模10取餘再除10,從個位按照移位不斷得到各個位置的數字,正好是結果從高位到低位的各個位置的數字,對結果的處理正好和原數相反,不斷乘10加餘數。
此題目需要注意的幾點是:
1. 首先對原數x按照幾個範圍進行劃分,a.-10<x<10的範圍直接返回x; b.其他情況;
2. 需要設定一個boolean類型變數來標記原數的符號,負數需要轉換為正數進行處理,結果再附加上符號;
3. 注意越界的情況,原數不會出現越界,但是反轉以後的數字會存在越界的情況!!!!
java代碼:
public class Solution { public int reverse(int x) { if(x>-10&&x<10) return x; boolean flag = x>0?true:false; long temp = x; long result =0; temp = temp>0?temp:-temp; while(temp>0) { result = result*10+temp%10; temp /=10; } if(result>Integer.MAX_VALUE){ return 0; }else if(flag) { return (int)result; }else { return -(int)result; } }}
leetcode----------Reverse Integer