New Java Solution for Reverse Integer


  • 0
    W

    Algorithm
    I used the reverse method of StringBuffer itself.

    class Solution {
        public int reverse(int x) {
            String str = "";
            int result = 0;
            StringBuffer sb = new StringBuffer(Integer.toString(x));
            if(x < 0){
                sb = new StringBuffer(sb.substring(1));
                str = "-";
            }
            str += sb.reverse().toString();
            try {
            	result = Integer.valueOf(str);
    	} catch (java.lang.NumberFormatException e) {
    			result = 0;
    	}
            return result;
        }
    }
    

    Complexity Analysis

    Time complexity: O(1).


Log in to reply
 

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