This question is part of NeetCode150 series.
Problem Description
Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array. leetcode
Solution
1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public int missingNumber(int[] nums) {
int ans = 0;
for(int i=0; i<nums.length; i++) ans ^= nums[i];
for(int i=1; i<=nums.length; i++) ans ^= i;
return ans;
}
}
Another way to code
1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public int missingNumber(int[] nums) {
int ans = nums.length;
for(int i=0; i<nums.length; i++) ans ^= nums[i] ^ i;
return ans;
}
}