标签:
反转一个整数的数位(注意溢出情况)
Reverse digits of an integer. Example1: x = 123, return 321 Example2: x = -123, return -321
1 public class Solution { 2 public int reverse( int x ){ 3 int m = x; 4 long res = 0; 5 while( m!=0 ){ 6 res = res * 10 + m % 10; 7 m /= 10; 8 } 9 if( res > Integer.MAX_VALUE || res < Integer.MIN_VALUE ) 10 return 0; 11 return (int)res; 12 } 13 }
1 //可以直接用String的reverse方法,但是效率低 2 public class Solution { 3 public int reverse( int x ){ 4 String orig = String.valueOf(Math.abs(x)); 5 StringBuilder res = new StringBuilder(); 6 if( x<0 ) 7 res.append(‘-‘); 8 for( int i=orig.length()-1; i>=0 ; i-- ) 9 res.append( orig.charAt(i) ); 10 try{ 11 x = Integer.parseInt(res.toString()); 12 }catch( NumberFormatException e ){ 13 x = 0; 14 } 15 return x; 16 } 17 }
O(n)
标签:
原文地址:http://www.cnblogs.com/hf-cherish/p/4572773.html