一、题目
Given a 32-bit signed integer, reverse digits of an integer. Example 1: Input: 123 Output: 321 Example 2: Input: -123 Output: -321 Example 3: Input: 120 Output: 21 Note: Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−2^31, 2^31 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
二、解题思路:
1、定义一个List集合; 2、定义一个循环,取出x中的每一位数并存入List集合中,当循环执行完时集合中每个元素的顺序已是x的倒序; 3、循环遍历集合,用元素乘以相应的位数,得到倒序后的数值; 4、判断结果是否越界,如越界则返回0,否则返回结果值。
三、代码实现
public int reverse(int x) {
List<Integer> originalList = new ArrayList<>();
double result = 0;
int temp = 0;
while (x != 0) {
temp = x % 10;
originalList.add(temp);
x = x / 10;
}
for (int i = 0; i < originalList.size(); i++) {
result = result + originalList.get(i) * (Math.pow(10, originalList.size() - 1 - i));
}
if (result < Math.pow(-2, 31) || result > Math.pow(2, 31) - 1) {
return 0;
} else {
return (int)result;
}
}