How can I find the missing number in an array with an integer between 1 and 100?
Here's what I did. What can I do next? Can anyone suggest? I am looking for a bitt solution.
public static void main(String args[]) {
// one missing number
printMissingNumber(new int[]{1, 2, 3, 4, 6}, 6);
// two missing number
printMissingNumber(new int[]{1, 2, 3, 4, 6, 7, 9, 8, 10}, 10);
// three missing number
printMissingNumber(new int[]{1, 2, 3, 4, 6, 9, 8}, 10);
// four missing number
printMissingNumber(new int[]{1, 2, 3, 4, 9, 8}, 10);
// Only one missing number in array
int[] iArray = new int[]{1, 2, 3, 5};
int missing = getMissingNumber(iArray, 5);
System.out.printf("Missing number in array %s is %d %n",
Arrays.toString(iArray), missing);
}
-1
koshish kharel
source
to share
2 answers
For n consecutive numbers, the sum s = n (n + 1) / 2.
Sum the numbers in the array and subtract them from s to find the missing number.
+2
sray
source
to share
If n
is the largest number, and only one is missing, then the missing number
n * (n + 1) / 2 - sum{elements in your array}
The first term is the sum of n
consecutive integers from 1 to including n
.
0
Bathsheba
source
to share