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.

More from C# Programming Tutorial

All questions for this course
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details