Derive it. Let the lowest set bit be at position k, so
x=high bitsa1k zeros0⋯0
Two's complement: −x=¬x+1. Flipping gives aˉ01⋯1; adding 1 ripples through the trailing ones:
−x=aˉ1k0⋯0
Now AND them. High bits: a&aˉ=0. Position k: 1&1=1. Trailing: 0&0=0.
x&−x=2k — exactly the isolated lowest set bit.
The least significant (rightmost) bit, place value 20=1.
XOR identity law?
a⊕0=a.
XOR self-inverse law?
a⊕a=0 (duplicates cancel).
How to find the element appearing once when all others appear twice?
XOR the whole array; pairs cancel, the unique value remains. O(n)/O(1).
What does x & -x compute, and why?
Isolates the lowest set bit (2k); two's complement keeps that bit aligned and cancels everything above.
What does x & (x-1) do?
Clears the lowest set bit.
Test for a power of two?
x != 0 && (x & (x-1)) == 0.
Brian Kernighan popcount complexity?
O(#set bits) — one set bit removed per loop.
x << k and x >> k equal what arithmetically?
x⋅2k and ⌊x/2k⌋.
Find the missing number in 0..n with XOR?
XOR all indices 0..n with all array elements; the missing value survives.
Why does XOR swap fail for aliased variables?
a ^= a zeros the value, so both end up 0.
Recall Feynman: explain to a 12-year-old
Imagine a row of light switches. XOR is a magic toggle: flip a switch twice and it's like you never touched it — so any number that shows up an even number of times disappears, and only the odd one is left glowing. x & -x is a flashlight that finds the lowest switch that's ON. And to count how many lights are on, Brian Kernighan's trick keeps turning off the lowest ON light one at a time and tallies how many times it did that.
Dekho, integer matlab sirf 0 aur 1 ka ek row — bits. Bit manipulation ka matlab hai un switches ko seedha chhedna, slow arithmetic ke bajaye. Teen main hathiyaar hain. Pehla XOR (^): jo bhi cheez do baar (even times) aaye, woh khud cancel ho jaati hai (a^a=0), aur a^0=a rehta hai. Isi se "array me sab elements do-do baar hain, ek single hai" wala problem ek hi loop me ho jaata hai — pure array ko XOR kar do, jo bacha woh answer.
Doosra trick: x & -x sabse neeche wala set bit (LSB jo ON hai) nikaal deta hai. Yeh two's complement ki wajah se kaam karta hai — -x matlab saare bits flip karke +1, isse lowest 1 bit exactly line up ho jaata hai aur upar sab cancel. Aur x & (x-1) sabse neeche wala set bit hata deta hai — isi se power-of-two check (x & (x-1) == 0) banta hai.
Teesra: set bits ginna (popcount). Naive way me har bit shift karke gino. Lekin Brian Kernighan ka trick smart hai — x &= x-1 har baar ek set bit udaata hai, toh loop sirf utni baar chalega jitne 1s hain. Sparse numbers ke liye bahut fast.
Yeh sab isliye important hai kyunki interview aur competitive coding me yeh tricks O(n) ya O(1) space me kaam karwa dete hain, bina extra hash set ke. Bas yaad rakho: XOR copies ko maarta hai, AND-minus low bit pakadta hai, minus-one low bit girata hai.