Thursday, April 24, 2014

Leetcode: Reverse Integer

Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321

Solution:

We keep the overflow checking in a comment as leetcode does not accept throwing exceptions, but in a real implementation this needs to be done

public class Solution {
    public int reverse(int x) {
        int sol = 0;
        while(x!=0)
        {
            //if (sol>=((Integer.MAX_VALUE-x%10)/10))
            //    throw new Exception("The number overflows");
            sol = sol * 10 + x % 10;
            x = x/10;
        }
        return sol;
    }
}

No comments :

Post a Comment