1

I was asked to reverse a long value without making use of any other types such as BigInteger, String, etc., to hold values while reversing it. I am allowed to use only long variables 'at max memory of long' as extra temporary variable while computing the result. I see difficulty in handling the "overflow" case while reversing the long value.

I did search the net for this specific problem, gone through this link:Java reverse an int value without using array to apply similar solution to integer, but I found solutions where they are using other data types to hold result values. For example, to reverse int, long is used to carry the result but what if you are forced to use only int to carry the result? and I am surprised that no one solved this problem without using other types. I am also wondering whether it's possible to do this? Please provide your inputs.

Function looks like this:

public int reverseLong(long value){

int sign =1;
long result=0; //to hold result

if(value < 0){
    value =-value;
    sign = -1;
}
while(value !=0){       
    result = result*10+value%10;
    value = value/10;   

    if(){ //could be a check on 'result' for overflow case
        throw new NumberFormatException();
    }
}

return sign*result;
}
Community
  • 1
  • 1
Prashanth Peddabbu
  • 92
  • 1
  • 1
  • 11

1 Answers1

2

As mentioned by @qwertyman in comments. This solution works fine.

public long reverseLong(long value){

    int sign = 1;
    long result=0; //to hold result

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

    while(value !=0){
    /*
    * To give a little perspective about how one can arrive at writing this
    * condition:- Think of long as some type which holds only 2 or 3 bits of
    * data. If it holds only 2 bits, then range of values it can hold will be
    * 0 to 3. Now it's easy to validate or arrive at conditions like the one 
    * in below.
    */  
    if(result > (Long.MAX_VALUE - value%10)/10){ 
       throw new NumberFormatException();
    }
    result = result*10+value%10;   
    value = value/10;
    }

 return sign*result;
}
Prashanth Peddabbu
  • 92
  • 1
  • 1
  • 11