Solution in java


  • 0
    S

    Solution

    Iterate through each digit of the number in reverse order and update reverse number. Return zero if there is an overflow.

    class Solution {
    	public int reverse(int x) {
    		int reverse = 0;
    		int sign = 1;
    		if (x < 0) {
    			x = -x;
    			sign = -1;
    		}
    		while (x > 0) {
    			int digit = x % 10;
    			int temp_reverse = reverse;
    			reverse = reverse * 10 + digit;
    			
    			if ( (reverse - digit) / 10 != temp_reverse) {
    				// Overflow
    				reverse = 0;
    				break;
    			}
    			x = x / 10;
    		}
    		return reverse * sign;
    	}
    }
    
    

    Explanation

    First check if it's a negative number. We store the sign in an integer and convert x to a positive integer if required.

    if (x < 0) {
      x = -x;
      sign = -1;
    }
    
    

    while loop will not exit till remaining number x is greater than zero. In each iteration we perform following steps.

    • Get the digit at place one

      int digit = x % 10;
      
    • Update reverse with this digit

      reverse = reverse * 10 + digit;
      
    • Check if there is an overflow

      if ( (reverse - digit) / 10 != temp_reverse) {
        // Overflow
        reverse = 0;
        break;
      }
      
    • Remove digit at place one in the original number

      x = x / 10;
      
      
    • Continue till ** x > 0 **


Log in to reply
 

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