力扣:7. 整数反转

思路:

例:

1.先将整数x 取余10,得到个位数,再得到除了个位数之外的整数,

2再重复操作,这次将上次得到的个位数乘10,再加上这次得到的个位数,如此便将原来最小的位数变成最大的位数;

3.依次将x中的数取出,加到反转的数中,得到结果。

实现:

1.先定义一个变量result接收反转后的结果,并将其先取0。

2.利用循环,将x%10得到整数x中的个位数,将result*10+x%10赋值给result,再让x/10,得到除了个位数之外的整数,循环至x=0。

3.题中要求对反转后的数是否合理进行判断:

即反转后的数不得超过int表示的范围,可用Integer.MAX_VALUE函数和Integer.MIN函数代表最大和最小值,再用if语句进行判断。

Integer.MAX_VALUE = 2^31-1=2147483647

Integer.MIN_VALUE = -2^31=-2147483648

if代码实现:

if (result > Integer.MAX_VALUE / 10 || (result == Integer.MAX_VALUE/10 && x % 10 > 7)) {

                return 0;

            }

if (result < Integer.MIN_VALUE / 10 || (result == Integer.MIN_VALUE/10 && x % 10 < -8)) {

                return 0;

            }

完整代码:

class Solution {
    public int reverse(int x) {
         int result = 0;
        while (x != 0) {
            if (result > Integer.MAX_VALUE / 10 || (result == Integer.MAX_VALUE/10 && x % 10 > 7)) {
                return 0;
            }
            if (result < Integer.MIN_VALUE / 10 || (result == Integer.MIN_VALUE/10 && x % 10 < -8)) {
                return 0;
            }
            result = result * 10 + x % 10;
            x = x / 10;
        }
        return result;
}
}

  • 7
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值