7. Reverse Integer [Easy]

第一种方法:

本题最快也最简便的方法是用long存储和更新倒转的数字,但其实不符合题中规定的只能存储32位int数值的环境

第二种方法:

转为StringBuffer,依次用append()、reverse()、toString()方法,获得倒转数值对应的字符串,再用Integer.parseInt() + try&catch尝试转换为int,成功则返回得到的int,exception说明倒转的数字超出int存储范围,return 0

/** 
 * 用long先存储res,再判断是否超出int范围,超出则return 0,未超出则return (int)res
 * 数字反转过程:
 * 每次x/=10的变化迭代,直到x=0
 * 在每一次循环中将当前res*10,将res中的每个位都在十进制中提高一位
 * 并取当前x的个位数temp=x%10(注意要取余而非取模),加到提高了一位的res中作为个位,res=res*10+temp
 * 这样每次循环,将已加入res的各个数字提高一位,并将当前x中的个位数加到res的个位,再用x/=10减掉x的最后一位,即每次将x中的一位移动到res中,得到res为x的倒转数字
 * Runtime: 1 ms
 */
class Solution {
    public int reverse(int x) {
        long res = 0;
        while (x != 0) {
            res = res * 10 + x % 10;
            x /= 10;
        }
        return res > Integer.MAX_VALUE || res < Integer.MIN_VALUE ? 0 : (int)res;
    }
}
/**
 * int ->
 * StringBuffer + append(x) + reverse() + toString() ->
 * String + Integer.parseInt() + try&catch(异常说明结果超出Integer范围,return 0)
 * Runtime: 3 ms
 */
class Solution {
    public int reverse(int x) {
        StringBuffer sb = new StringBuffer();
        String resS;
        if (x < 0) {
            x = -x;
            resS = "-" + sb.append(x).reverse().toString();
        } else
            resS = sb.append(x).reverse().toString();
        try {
            return Integer.parseInt(resS);
        } catch (Exception e) {
            return 0;
        }
    }
}
/**
 * 自己的代码
 * 将数字去掉符号转换为字符串,遍历(一半)字符串做倒置,最后加上符号parseInt,成功则返回得到的值,失败则return 0
 * 时间复杂度已经很低了O(n/2),但比起其他解答效率还是很低
 * Runtime: 20 ms, faster than 6.26%
 * Memory Usage: 39.5 MB, less than 5.67%
 */
class Solution {
    public int reverse(int x) {
        String s1 = "", s2 = "";
        if (x < 0) {
            s1 += "-";
            x = -x;
        }
        String x_s = x + "";
        
        int length = x_s.length();
        for (int i = 0; i < length / 2; i++) {
            s2 = x_s.charAt(i) + s2;
            s1 += x_s.charAt(length - 1 - i);
        }
        try {
            return Integer.parseInt((length & 1) == 1 ? s1 + x_s.charAt(length / 2) + s2 : s1 + s2);
        } catch (NumberFormatException e) {
            return 0;
        }
    }
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值