Mid
From PDF
Coding
C# Coding Interview
Find the missing number in a sequence from 1 to n using XOR?
public int FindMissingNumber(int[] nums, int n) {
int xor = 0;
for (int i = 1; i <= n; i++) {
xor ^= i;
}
foreach (int num in nums) {
xor ^= num;
}
return xor;
}
Follow on:
Explanation:
XOR all numbers from 1 to n and XOR all elements in array; duplicates cancel out, leaving
missing number.
Share this Q&A
Share preview image: https://www.toolliyo.com/images/toolliyo-logo.png