LeetcodeLeetCodeアルゴリズムパンチカード学習7日目

2、整数反転

32ビットの符号付き整数xを指定し、xの各桁の反転の結果を返します。

反転後、整数が32ビットの符号付き整数の範囲[-231、231 -1]を超えると、0が返されます。

環境が64ビット整数(符号付きまたは符号なし)の格納を許可していないと想定します。

1.私の

class Solution {
    
    
    public int reverse(int x) {
    
    
        boolean check=false;
        if(x<0){
    
    
            x=-x;
            check=true;
        }
        int minnum=-2147483648;
        int maxnum=2147483647;
        long y=0;
        
        while(x!=0){
    
    
            y=y*10+x%10;
            x=x/10;
        }
        if(y<=minnum || y>=maxnum){
    
    
            return 0;
        }
        
        if(check){
    
    
            y=-y;
        }
        int m=(int)y;
        return m;
    }
}

2.公式

class Solution {
    
    
    public int reverse(int x) {
    
    
        int rev = 0;
        while (x != 0) {
    
    
            int pop = x % 10;
            x /= 10;
            if (rev > Integer.MAX_VALUE/10 || (rev == Integer.MAX_VALUE / 10 && pop > 7)) return 0;
            if (rev < Integer.MIN_VALUE/10 || (rev == Integer.MIN_VALUE / 10 && pop < -8)) return 0;
            rev = rev * 10 + pop;
        }
        return rev;
    }
}

作者:LeetCode
链接:https://leetcode-cn.com/problems/reverse-integer/solution/zheng-shu-fan-zhuan-by-leetcode/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

3.コメント欄にかなり良いものを見ました

public int reverse(int x) {
    
    
	int ans = 0;
	while (x != 0) {
    
    
		if ((ans * 10) / 10 != ans) {
    
    
			ans = 0;
			break;
		}
		ans = ans * 10 + x % 10;
		x = x / 10;
	}
	return ans;
}

おすすめ

転載: blog.csdn.net/Shadownow/article/details/114066553