Simple Java Solution


  • 0
    T
        public int reverse(int x) {
         
            StringBuilder builder = new StringBuilder();
            
            String numstr = String.valueOf(x);
            builder.append(numstr);
            String reversedStr = builder.reverse().toString();
            
            if('-' == reversedStr.charAt(reversedStr.length() - 1)) {
                builder.deleteCharAt(reversedStr.length() - 1);
                reversedStr = '-' + builder.toString();      
            }
            
            try {
             if(Integer.parseInt(reversedStr) > Integer.MAX_VALUE || Integer.parseInt(reversedStr) < Integer.MIN_VALUE) {
                return 0;
                }
            }
             catch (NumberFormatException e) {
                return 0;
            }
            
            return (int) Integer.parseInt(reversedStr);    
            
    }
    

    Works for all unsigned ints. O(1) time complexity.


Log in to reply
 

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