Q5. An array contains all the integers from 1 to n except for one number which is missing (so there are n-1 elements in array). Write code to find the missing integer.
Answer:
public class Arrays5 {
public static int findMissing(int[] a) {
int n = a.length + 1;
int sum = 0;
for (int num : a) {
sum += num;
}
int sigmaN = n * (n + 1) / 2;
return sigmaN - sum;
}
public static int findMissing2(int[] a) {
int n = a.length + 1;
int missing = 1;
for (int i = 2; i <= n; i++) {
missing ^= i;
}
for (int num : a) {
missing ^= num;
}
return missing;
}
public static void main(String[] args) {
int[] a1 = { 1, 2, 4, 5, 6, 7 }; // 3 is missing from 1 to 7
System.out.println(findMissing(a1));
int[] a2 = { 1, 2, 3, 4, 5, 6, 7 }; // 8 is missing from 1 to 8
System.out.println(findMissing(a2));
System.out.println(findMissing2(a1));
System.out.println(findMissing2(a2));
}
}
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.