学习时间:
2023年1月27日
题目描述:
题解分享:
/**
* @ Author 繁华倾夏
* @ Date 2023年01月27日
*/
// 力扣(LeetCode):7. 整数反转
public class Solution {
public static int reverse(int x) { // 调用函数
int u;
if(x==0){ // 判断是否为0,为0时可以直接返回
return 0;
}else if(x<0){ // 小于0时,使用u记录符号
u=-1;
x=-x; // 并使x为正,方便接下来的运算
}else{
u=1; // 大于0时,赋u为1
}
int s=0;
int t=0;
while(x!=0){ // 遍历x
if(t>Integer.MAX_VALUE/10||t<Integer.MIN_VALUE/10){ // 判断当前数值是否越界
return 0;
}
s=x%10; // 取到各位数值
t=t*10+s; // 反向相乘
x/=10;
}
t*=u; // 判断符号
return t; // 不越界则正常输出
}
// 测试用例
// 输入 x = 123
// 输出 321
public static void main(String[] args) {
int x=123;
int re=reverse(x);
System.out.println(re);
}
}