gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:41:47 31 4
gpt4 key购买 nike

我被要求在不使用任何其他类型(例如 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/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com