Java, Python, C solutions


  • 0

    Python Solution

        def reverse(self, x):
            if x >= 0:
                p = int(str(x)[::-1])
                return 0 if p > 0x7FFFFFFF else p
            else:
                n = -int(str(x)[len(str(x))-1:0:-1])
                return 0 if n < -0x80000000 else n
    

    C Solution

    #include <limits.h>
    
    int reverse(int x)
    {
        long long r = 0;
        while (x != 0)
        {
            r = r * 10 + x % 10;
            x /= 10;
        }
        return (r < INT_MIN || r > INT_MAX) ? 0 : r;
    }
    

    Java Solution
    This one could be super similar to the C Solution. Here's a different looooong approach with unnecessary stuff

    public int reverse(int x) {
    	int neg = 1, degree = 0, rep = 0;
    	long r = 0l;
    	if (x == 0 || x == Integer.MIN_VALUE)
    		return 0;
    	neg = x < 0 ? -1 : 1;
    	x = x < 0 ? x * -1 : x;
    	degree = (int) Math.pow(10, (int) Math.log10(x));
    	// main loop after lots of crap
    	while (x != 0) {
    		int t = x / degree;
    		r += (long) Math.pow(10, rep++) * t;
    		if (r > Integer.MAX_VALUE)
    			return 0;
    		x %= degree;
    		degree /= 10;
    	}
    	return (int) r * neg;
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.