一、題目
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;
}
}