Java, using string to solve this, accepted but not sure if it is efficient.


  • 0
    B
    public int reverse(int x) {
        String s = Integer.toString(x);
    	if(s.charAt(0)==new Character('-')){
    		s = s.substring(1);
    	}
    	System.out.println(s);
    	StringBuffer sb = new StringBuffer();
    	for(int j=s.length()-1;j>-1;j--){
    		sb.append(s.charAt(j));
    	}
    	if(x<0) sb.insert(0, "-");	
    	long l = Long.parseLong(sb.toString());
    	
    	if(l>(Math.pow(2,31)-1) || l<(Math.pow(-2,31))){
    		return 0;
    	}else{
    		return Integer.parseInt(sb.toString());
    	}
    }

  • 0
    J

    Instead of l > (Math.pow(2,31) - 1), you could use l > Integer.MAX_VALUE. That would make your code easier to read.


  • 0
    B

    Yep, I just realize that. Thanks~


Log in to reply
 

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