您好,登錄后才能下訂單哦!
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;
}
}
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。