标签:
Reverse Integer
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
若反转的数溢出,直接返回0
可以用计算结果来判断溢出,也可以用因数来判断
Java代码实现:
1 public class ReverseInteger { 2 public static int reverseInt(int x){ 3 if (x == 0) { 4 return 0; 5 } 6 int flag = -1; 7 int result = 0; 8 if (x < 0) { 9 x = x * flag; 10 if (x < 0) { 11 return 0; 12 } 13 } else { 14 flag = 1; 15 } 16 int digits = 1; 17 int temp = x; 18 while(temp/10 != 0){ 19 digits++; 20 temp/=10; 21 } 22 //judge before calculate at every may out of range place 23 for (int i = 1; i <= digits; i++) { 24 int a,b; 25 a = (int) (x/Math.pow(10, i-1)); 26 a = a%10;//get the single number 27 b = (int) Math.pow(10, digits-i); 28 if ((a*b<0) || (a > 2 && (digits - i) == 9)) {//use number to judge 29 return 0; 30 } else { 31 temp = a*b; 32 } 33 if (result + temp < 0) {//judge 34 return 0; 35 } else { 36 result += temp; 37 } 38 } 39 return result*flag; 40 } 41 public static void main(String args[]){ 42 int max = 2147483647; 43 int min = -2147483648; 44 System.out.println(reverseInt(0)); 45 System.out.println(reverseInt(1534236469)); 46 System.out.println(reverseInt(-2133847412)); 47 } 48 }
输出:
0
0
-2147483312
Reverse Integer - 反转一个int,溢出时返回0
标签:
原文地址:http://www.cnblogs.com/rustfisher/p/4808413.html