2. Java- 整数反转

文章目录

package com.dhl.beyond;

/**
 * 给你一个 32 位的有符号整数 x ,返回 x 中每位上的数字反转后的结果。
 * <p>
 * 如果反转后整数超过 32 位的有符号整数的范围 [−231,  231 − 1] ,就返回 0。
 * <p>
 * 假设环境不允许存储 64 位整数(有符号或无符号)。
 */

public class 整数反转 {
    
    
    public static void main(String[] args) {
    
    
        System.out.println(reverse(-34233111));

    }


    public static int reverse(int x) {
    
    
        if (x == Integer.MIN_VALUE) return 0;
        int neg = x < 0 ? -1 : 1;
        x *= neg;
        int ret = 0;
        while (x > 0) {
    
    
            int n = ret;
            n *= 10;
            n += x % 10;
            x /= 10;
            if (n / 10 != ret) return 0;
            ret = n;
        }
        return ret * neg;
    }
}

方式一

   public int reverse(int x) {
    
    
         int neg = x < 0 ? -1 : 1;
         x *= neg;
         int i = 0;
        String str = "";
        if (x == Integer.MIN_VALUE) return 0;      
            str = Math.abs(x)+"";
            StringBuilder s2 = new StringBuilder();
            s2.append(str);
            String s = s2.reverse().toString();
            if(Double.parseDouble(s) > Integer.MAX_VALUE){
    
    
                return  0;
            }

      
        return Integer.parseInt(s)*neg;
    }

方式二:

 public static int reverse(int x) {
    
    
        if (x == Integer.MIN_VALUE) return 0;
        int neg = x < 0 ? -1 : 1;
        x *= neg;
        int ret = 0;
        while (x > 0) {
    
    
            int n = ret;
            n *= 10;
            n += x % 10;
            x /= 10;
            if (n / 10 != ret) return 0;
            ret = n;
        }
        return ret * neg;
    }

猜你喜欢

转载自blog.csdn.net/Beyond_Nothing/article/details/113998091