Using StringBuffer solve Reverse Integer problem

LeetCode: https://leetcode.com/problems/reverse-integer/description/

The below Solution 1 is the most popular solution we can find online.
But here is another way (Solution 2) to solve the problem with StringBuffer.

The Solution 2 is easier to understand and the code is cleaner.

Solution 1:

class Solution {
    public int reverse(int x) {
        int result = 0;
        boolean isNegative = false;
        int max = Integer.MAX_VALUE / 10;

        if(x == 0 || x >= Integer.MAX_VALUE || x <= Integer.MIN_VALUE)
            return 0;

        if(x  max)
                return 0;
            result = result * 10 + x %10;
            x= x/10;
        }

        if(isNegative)
            return -result;
        else
            return result;
    }
}

Solution 2:

class Solution {
    public int reverse(int x) {
        try {
            StringBuffer sb = new StringBuffer(String.valueOf(x));
            sb.reverse();
            int lastPosition = sb.length() - 1;

            if (sb.charAt(lastPosition) == '-') {
                sb.deleteCharAt(lastPosition);
                sb.insert(0, '-');
            }

            return Integer.parseInt(sb.toString());
        } catch (NumberFormatException e) {
            e.printStackTrace(System.err);
            return 0;
        }
    }
}

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 )

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s