码迷,mamicode.com
首页 > 其他好文 > 详细

反转整数

时间:2018-08-09 23:18:07      阅读:214      评论:0      收藏:0      [点我收藏+]

标签:mat   abs   rip   ber   oid   exce   sys   ems   leetcode   

反转整数

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;
        }

    }
}

 

反转整数

标签:mat   abs   rip   ber   oid   exce   sys   ems   leetcode   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!