Solution for Reverse Integer-Java


  • 0
    J

    Approach #7 Reverse Integer-Java

    Intuition

    Double check on both input and output to ensure no overflow

    Algorithm

    Java

    private int reverseInteger(int inputNum) {
    		long result=0;	//use long to avoid overflow result
    		int positiveMark=1;	//actually positive and negative mark do not affect calculation
    		
    		if(inputNum==0||inputNum>=Integer.MAX_VALUE||inputNum<=Integer.MIN_VALUE){
    			return 0;
    		}else if(inputNum<0){
    			//to prove the mark problem, remove whole if statement
    			positiveMark=-1;
    			inputNum=Math.abs(inputNum);
    		}
    		
    		while(inputNum!=0){
    			if(result>Integer.MAX_VALUE){
    				return 0;
    			}
    			result=result*10+inputNum%10;
    			inputNum=inputNum/10;
    		}
    		
    		if(result>Integer.MAX_VALUE){
    			return 0;
    		}else{
    			return (int) (result*positiveMark);
    		}
    	}
    

    Complexity Analysis



Log in to reply
 

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