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;
}