反转整数

反转整数

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

    }
}

 用stringbuilder可以进行字符串反转

还可以直接把字符串进行替换;

如果是数的交换,可以

a = a + b;

b = a - b

a = a - b

容易溢出;

用那个异或竟然可以交换整数;

public class Lesson002 {
    public static void main(String[] args) {
        int i = 2147483647;
        int j = -2147483648;
        i = i^j;
        j = j^i;
        i = i^j;
        System.out.println(i);
        System.out.println(j);
    }
}

 

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