leetcode

Reverse Integer

Reverse digits of an integer.

Example1: x = 123, return 321

Example2: x = -123, return -321

Formula = result*10 + x%10

123

  • 0*10 + 3 = 3
  • 3*10 + 2 = 32
  • 32*10 + 1 = 321
public int reverse(int x) {    
        long results = 0;
        while (x!=0) {
            results = results * 10 + x % 10;
            x = x/10;
        }

        if (results>Integer.MAX_VALUE || results<Integer.MIN_VALUE) {
            return 0;
        }
        return (int)results;
    }