【LeetCode】整数反转

package leetcode.editor.cn;

//给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。 
//
// 示例 1: 
//
// 输入: 123
//输出: 321
// 
//
// 示例 2: 
//
// 输入: -123
//输出: -321
// 
//
// 示例 3: 
//
// 输入: 120
//输出: 21
// 
//
// 注意: 
//
// 假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [−231, 231 − 1]。请根据这个假设,如果反转后整数溢出那么就返回 0。 
// Related Topics 数学

public class 整数反转 {
    public static void main(String[] args) {
        Solution solution = new 整数反转().new Solution();
        System.out.println(solution.reverse(1534236469));
        System.out.println(-21 / 10);
        System.out.println(-21 % 10);

    }
    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        /**
         * 方案一:数字循环
         * 通过循环将数字x的每一位拆开,在计算新值时每一步都判断是否溢出。
		 * 溢出条件有两个,一个是大于整数最大值 Integer.MAX_VALUE,另一个是小于整数最小值 Integer.MIN_VALUE,设当前计算结果为 num,下一位为 temp。
		 * 从 num * 10 + temp > Integer.MAX_VALUE 溢出条件来看
		 * 	当出现 num / 10 > Integer.MAX_VALUE 且还需要添加 temp 时,一定溢出。
		 * 	当出现 num == Integer.MAX_VALUE / 10 时,且 temp > 7 时,一定溢出,7 是 Intger.MAX_VALUE 的个位数。
		 * 从 num * 10 + temp < Integer.MIN_VALUE 溢出条件来看
		 * 	当出现 num / 10 < Integer.MIN_VALUE 且还需要添加 temp 时,一定溢出。
		 * 	当出现 num == Integer.MIN_VALUE / 10 时,且 temp < -8 时,一定溢出,-8 是 Intger.MIN_VALUE 的个位数。
         * @param x
         * @return
         */
        public int reverse(int x) {
            try {
                int num = 0;
                while (x != 0) {
                    int temp = x % 10;
                    if (num > Integer.MAX_VALUE / 10 || (num == Integer.MAX_VALUE / 10 && temp > 7)){
                    	return 0;
					}
                    if (num < Integer.MIN_VALUE / 10 || (num == Integer.MIN_VALUE / 10 && temp < -8)){
						return 0;
					}
					num = num * 10 + temp;
                    x = x / 10;
                }
                if (num > Integer.MAX_VALUE || num < Integer.MIN_VALUE) {
                    return 0;
                }
                return num;
            } catch (Exception e) {
                return 0;
            }
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

    /**
     * 方案二:字符传反转
     * 常识:10 * -1 = -10;-10 * -1 = 10;-21 % 10 = -1;-21 / 10 = -2
     * 分析:判断数字是否大于0,在利用 reverse 函数进行反转。
     */
    public int reverse1(int x) {
        try {
            int b = 1;
            if (x < 0) {
                x = x * -1;
                b = -1;
            }
            StringBuffer stringBuffer = new StringBuffer(String.valueOf(x));
            x = Integer.valueOf(stringBuffer.reverse().toString());
            x = x * b;
            return x;
        } catch (Exception e) {
            return 0;
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值