力扣7:整数反转
import java.util.*; class Solution { public int reverse(int x) { int flag = x; if(flag < 0){ x = -x; } int num = 0; //返回后的数字 long lnum = 0;//用更长范围,来比较是否出错,确实比较low String str = Integer.toString(x); char arr[] = str.toCharArray(); Reverse(arr); for(int i = 0; i < arr.length;i++){ num = (arr[i]-'0') + num*10; lnum = (arr[i]-'0') + lnum*10; if(num!=lnum){ return 0; } } if(flag > 0) return num; else return -num; } public void Reverse(char str[]){ int len = str.length; char temp; for(int i = 0;i < len/2;i++){ temp = str[i]; str[i] = str[len - 1 - i]; str[len - 1 -i] = temp; } } }
判断溢出比较麻烦。num做计算处try catch不知道为什么就是不行。