给定一个 32 位有符号整数,将整数中的数字进行反转。
示例 1:
输入: 123
输出: 321
示例 2:
输入: -123
输出: -321
示例 3:
输入: 120
输出: 21
注意:
解:比较简单,做数学题记住使用%和/的应用。
class Solution {
public int reverse(int x) {
//long保存有可能会溢出int的数
long result = 0;
while (x != 0) {
//对10取余求末尾的数
int tail = x % 10;
long newResult = result * 10 + tail;
//溢出直接返回0
if (newResult > Integer.MAX_VALUE || newResult < Integer.MIN_VALUE) {
return 0;
}
result = newResult;
x = x / 10;
}
return (int) result;
}
}
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有