Reverse Integer

Reverse digits of an integer.

译:反转一个整数的数字

Example1: x = 123, return 321

Example2: x = -123, return -321

click to show spoilers.

Have you thought about this?Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!If the integer’s last digit is 0, what should the output be? ie, cases such as 10, 100.Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

译:你仔细思考过么?写代码前需要考虑到的一些问题,比如你已经考虑到这个整数的最后一个数为0,那么我们应该输出什么呢?例如:输入10,100。你注意到反转的数可能会溢出吗?假设你输入了一个32位的整数,如1000000003反过来就会导致溢出。那你怎么处理这些情况呢?所以对于这个问题来说我们假设如果你反转的数是溢出的,那么就指定它返回0。

public class ReverseInteger {

public int reverse(int x) {

boolean isNegativeNum = false;

if (x == 0) return 0; // 考虑到为0的情况直接返回0

if (x < 0) {

// 如果该数为负数,则使用标志位,并且为了去掉符号实用Math.abs()这个方法取绝对值

isNegativeNum = true;

x = Math.abs(x);

}

String xString = String.valueOf(x);

String result = "";

int index = xString.length();

// 时间复杂度最糟为O(n)

for (int i = index - 1; i >= 0; i--){

result += String.valueOf(xString.charAt(i));

}

try{

// 此处投机取巧,由于反转后的数可能溢出,导致NumberFormatException,

//所以一旦catch该异常就指定该数为0

if (!isNegativeNum) return Integer.valueOf(result);

else return (- Integer.parseInt(result));

} catch (NumberFormatException e){

e.printStackTrace();

return 0;

}

}

}

你可能感兴趣的:(Reverse Integer)