Reverse Integer

Problem:

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

Comment:

If the integer’s last digit is 0, what should the output be? ie, cases such as 10, 100. — Assume as 01 and 001

Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases? — To return some default value, however leetcode does not have a case that causes overflow.

Throw an exception? Good, but what if throwing an exception is not an option? You would then have to re-design the function (ie, add an extra parameter).

 


public class Solution {
    public int reverse(int x) {
        String X = Integer.toString(x);
        
        StringBuilder sb = new StringBuilder();
        
        int start = 0;
        
        if (X.charAt(start) == '-') {
            sb.append('-');
            start++;
        }
        
        for (int i = X.length() - 1; i >= start; i--) {
            sb.append(X.charAt(i));
        }
        
        return Integer.valueOf(sb.toString());
        
    }
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s