[Java] Using StringBuilder, Instead of Using Long


  • 0
    L

    The main idea is to append x%10 to string and discard the last digit by x=x/10
    until x is 0.

    To deal with overflow, use try/catch to see if Integer.valueOf(string) is successful.

    public int reverse(int x) {
    	StringBuilder sb = new StringBuilder();
    	sb.append(x < 0 ? "-" : ""); // check if x is negative
    	x = Math.abs(x);
    	while (x % 10 == 0 && x > 0) { // if x is ended with one or more 0s, discard these 0s
    		x /= 10;
    	}
    	while (x > 0) { // append the last digit of x to sb, then discard the last digit
    		sb.append(x % 10);
    		x /= 10;
    	}	
    	int result = 0;
    	try {
    		result = Integer.valueOf(sb.toString()); // the number in sb is not overflow
    	} catch (NumberFormatException e) {
    		result = 0; // overflow
    	}
    	return result;
    }
    

Log in to reply
 

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