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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。