Leetcode LeetCode algorithm punch card learning day 7

Two, integer inversion

Give you a 32-bit signed integer x, and return the result of the inversion of each digit in x.

If the integer exceeds the 32-bit signed integer range [−231, 231 − 1] after the inversion, 0 is returned.

Assume that the environment does not allow storage of 64-bit integers (signed or unsigned).

1. My

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. Official

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. I saw a good one in the comment area

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

Guess you like

Origin blog.csdn.net/Shadownow/article/details/114066553