我为Hackerrank挑战写了一个解决方案,其中我将大量的数字总和为一个总变量。当我使用整数时,我注意到我在一个测试用例中溢出,但所有其他测试用例都输出了正确的答案。当我将我的total
变量切换到很长时间以避免溢出时,我开始在两个测试用例(与之前相同并且另一个)溢出。一旦我将total
,numToSell
,和lastMax
改为长整数,程序就会计算出正确的答案。在long中使用long会导致java中溢出的额外情况。为什么?
什么会导致这种情况发生?我期望从int到long的变量不应该导致溢出。
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int T = in.nextInt();
while(T-->0)
{
int N = in.nextInt();
int[] price = new int[N];
for(int i = 0; i < N; ++i)
{
price[i] = in.nextInt();
}
int lastMax = price[N-1]; //works when this and numToSell are longs
int numToSell = 0;
long total = 0; //if this is also an int, only overflows in one case in my samples
for(int i = N - 2; i >= 0; --i)
{
if(price[i] <= lastMax)
{
++numToSell;
total -= price[i];
}
else
{
total += numToSell*lastMax;
lastMax = price[i];
numToSell = 0;
}
}
total += numToSell*lastMax;
System.out.println(total);
}
}
}
在受影响的试验情况下,N是39384和阵列中的每个数字是是整数1和100000
你能提供导致问题的最小量的输入数据吗? – Bohemian 2014-09-19 02:36:39
我想你可以使用调试器来回答你自己的问题,也许可以对变量的符号进行一些抽查。 – 2014-09-19 02:44:53