2016-07-15 43 views
1

我被要求在不使用任何其他类型(例如BigInteger,String等)的情况下反转一个长整型值,以便在反转它时保留值。在计算结果时,我只允许使用'最大内存长'的长变量作为额外的临时变量。我认为在扭转长期价值的同时处理“溢出”案件存在困难。如何反转长整型值并处理java中的溢出情况?

我没有搜索网络的这个特定的问题,通过这个链接:Java reverse an int value without using array申请类似的解决方案整数,但我找到解决方案,他们正在使用其他数据类型来保存结果值。例如,要反转int,使用long来传递结果,但如果仅仅使用int来传递结果呢?我很惊讶没有人不使用其他类型就解决了这个问题。我也想知道是否有可能做到这一点?请提供您的输入。

功能如下:

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

所以基本上'123'变成了'321'? –

+1

http://stackoverflow.com/a/4808804/4941367可能会有所帮助。 – Jeremy

+0

是的,123变成321,-345变成-543,并且2,147,483,647因为有溢出而给出例外。 –

回答

2

正如意见中提到的@qwertyman。此解决方案正常工作。

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