[英]Counting Inversions for an Array of 100,000 Integers, Why Get a Negative Output?
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class InversionCounter {
public static void main(String[] args) {
Scanner scanner = null;
try {
scanner = new Scanner(new File("src/IntegerArray.txt"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int [] nums = new int [100000];
int i = 0;
while(scanner.hasNextInt()){
nums[i++] = scanner.nextInt();
}
System.out.println(countInversions(nums));
}
public static int countInversions(int[] nums) {
int count = 0;
for (int i=0;i<nums.length-1;i++) {
for (int j=i+1;j<nums.length;j++) {
if (nums[i]>nums[j]) {
count++;
}
else {continue;}
}
}
return count;
}
}
The code above reads 100,000 integers from a file and counts the inversions for this array of integers. 上面的代码从文件中读取100,000个整数,并计算此整数数组的取反数。 The output is probably a very large number like 1198233847 and should definitely be positive. 输出可能是非常大的数字,例如1198233847,并且绝对应该是正数。 However, it outputs a negative one like -1887062008. 但是,它输出负值,如-1887062008。 The program logic is likely to be correct as I have tried other algorithms for the same purpose and got the same negative number as output. 程序逻辑很可能是正确的,因为我出于相同的目的尝试了其他算法并获得与输出相同的负数。 I suspect that the result is too big a positive number and as a result Java converts it to a negative one. 我怀疑结果太大了,所以Java将其转换为负数。
The max value of an int
is 2,147,483,647 - what you are seeing is overflow. 一个int
的最大值是2,147,483,647-您看到的是溢出。 You should make count
a long
if you expect it to be so big. 如果您希望count
如此之大,则应long
count
。
source: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html 来源: http : //docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
The worst case here is 4,999,950,000 inversions, which is bigger than int's max value (2,147,483,647). 最坏的情况是4,999,950,000个反转,它比int的最大值(2,147,483,647)大。 You should probably use a long to store the number. 您可能应该使用长号来存储数字。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.