Reverse in Java


  • 0
    T

    public static int reverse(int x) throws NumberFormatException{
    /String str = Integer.toString(x);
    StringBuffer sb = new StringBuffer();
    if(str.contains("-")){
    sb.append(str);
    sb.deleteCharAt(0);// I dont know why here would throw an exception :for input String ""
    sb.append("-");
    }
    sb.reverse();
    return Integer.valueOf(sb.toString().trim());
    /

        String str = Integer.toString(x);
        char[] chars = str.toCharArray();
        StringBuffer buf = new StringBuffer();
        for(int i=chars.length-1; i>=0 ; i--){
            buf.append(Character.toString(chars[i]));
        }
        
        if(x < 0){
            buf.deleteCharAt(chars.length -1 );
            buf.insert(0,'-');
        }
        return Integer.parseInt(buf.toString());
    }

Log in to reply
 

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