Solution in Java


  • 0
    G
    class Solution {
        public int reverse(int x) {
            String strX = "" + x;
            
            if (strX.length() == 1) return x;
            
            int startX = 0, endX = strX.length() - 1;
            
            char[] input = strX.toCharArray();
            
            if (input[0] == '-') startX = 1;
            
            while(startX <= endX) {
                swap(input, startX, endX);
                startX++;
                endX--;
            }
            
            try {
                return Integer.parseInt(new String(input));    
            } catch (Exception e) {
                return 0;
            }
            
        }
        
        public void swap(char[] input, int startX, int endX) {
            char temp = input[startX];
            input[startX] = input[endX];
            input[endX] = temp;
        }
    }
    

Log in to reply
 

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