Algorithms - Integer reversal
Gives a 32-bit signed integer, you need this integer number on each inverted.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
Note:
Suppose we have an environment can store the 32-bit signed integer, then the value range [-2 ^ 31 ^ 31 -2 - 1] Please According to this hypothesis, if the reverse integer overflow it returns 0 .
Source: stay button (LeetCode)
class Solution {
public int reverse(int x) {
String origNum = String.valueOf(x);
char[] charArr = origNum.toCharArray();
String reverse = "";
if(charArr[0] == '-'){
reverse = "-";
for(int i = charArr.length-1; i>0;i--){
reverse += charArr[i];
}
}
else{
for(int i = charArr.length-1; i>=0;i--){
reverse += charArr[i];
}
}
int num;
try{
num = Integer.parseInt(reverse);
}
catch(Exception e){
return 0;
}
num = Integer.parseInt(reverse);
if(num<Math.pow(-2,31) || num>Math.pow(2,31) ){
num = 0;
}
return num;
}
}
Note :
1, various data conversion method
int String transfer method using:
int x;
String y = String.valueOf(x);
String turn int method:
int z = Integer.parseInt(y);
String to String array:
char[] charArray = y.toCharArray();
2, exception handling
try{
}
catch(Exception e){
//此处为对异常如何处理
//比如,遇见异常后,返回某个值
}
Common abnormalities
3, JAVA power calculation
31 -2 power:
Math.pow(-2,31)