您的位置:首页 > 其它

Reverse Integer

2015-06-23 21:06 204 查看

1. Question

反转一个整数的数位(注意溢出情况)

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321


2. Solution

2.1 整除取余法

//可以直接用String的reverse方法,但是效率低
public class Solution {
public int reverse( int x ){
String orig = String.valueOf(Math.abs(x));
StringBuilder res = new StringBuilder();
if( x<0 )
res.append('-');
for( int i=orig.length()-1; i>=0 ; i-- )
res.append( orig.charAt(i) );
try{
x = Integer.parseInt(res.toString());
}catch( NumberFormatException e ){
x = 0;
}
return x;
}
}


View Code

3. 复杂度分析

O(n)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: