首页 > 其他 > 详细

反转整数

时间:2018-08-09 22:47:06      阅读:132      评论:0      收藏:0      [点我收藏+]

反转整数

https://leetcode-cn.com/problems/reverse-integer/description/

package com.test;

public class Lesson002 {
    public static void main(String[] args) {
        int input = -2147483648;
        System.out.println(getReverse(input));
    }

    private static int getReverse(int x) {
        int signal = 1;
        if (x < 0) {
            signal = -1;
        }
        if (x == 0) {
            return 0;
        }
        int inputAbs = Math.abs(x);
        // 处理-2147483648问题
        if (inputAbs < 0) {
            return 0;
        }
        // 如果大于1亿,就看个位数是否大于2;
        if (inputAbs > 1000000000) {
            int i00 = inputAbs % 10;
            if (i00 > 2) {
                return 0;
            }
        }
        int mod = 10;
        String res = "";
        // 不停的取余
        while (inputAbs >= mod) {
            int i = inputAbs % mod;
            res = res + i;
            // 每次取余都进行取余之后的除10处理
            inputAbs = inputAbs/mod;
        }
        // 最后剩余的数位也要加上
        res = res + inputAbs;
        try {
            return signal*Integer.parseInt(res);
        } catch (NumberFormatException e) {
            return 0;
        }

    }
}

 

反转整数

原文:https://www.cnblogs.com/stono/p/9452164.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!