- Simply use XOR the numbers in the array with the indices in the array and you will get the missing number.
Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | import java.util.*; public class HelloWorld{ public static void main(String []args){ int[] nums = {0, 1, 2, 4, 5}; System.out.println(missingNumber(nums)); } public static int missingNumber(int[] nums) { int xor = 0, i = 0; for (i = 0; i < nums.length; i++) { xor = xor ^ i ^ nums[i]; } return xor ^ i; } } |