algorithm - 如何反转长值并处理 java 中的溢出情况?

标签 algorithm data-structures

我被要求在不使用任何其他类型(例如 BigInteger、String 等)的情况下反转 long 值,以便在反转它时保存值。在计算结果时,我被允许只使用长变量“在最大内存中”作为额外的临时变量。我发现在反转 long 值时很难处理“溢出”情况。

我确实在网上搜索了这个具体问题,通过这个链接: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;
}

最佳答案

正如@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;
}

关于algorithm - 如何反转长值并处理 java 中的溢出情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38401546/

相关文章:

algorithm - 背包算法变量

algorithm - 尽可能将学生安排在尽量减少作弊的位置

algorithm - 变量 m 更新了多少次

algorithm - graph - 如何避免在深度优先搜索中重复处理相同的边缘?

algorithm - 从 n^2 减少时间复杂度

python - 如何避免冗余并将过滤器应用于字符串组合

java - 二 fork 树的最左节点和最右节点是什么?

python - 为什么退出递归调用时保留一些变量或列表,而另一些则不保留?

algorithm - 使用红/黑树实现 Dijkstra 的最短路径算法?

Java:合并排序是 O(N^2) 还是 O(N Log(N))