Algorithms and Data Structures · Middle · Question 62 of 75

What does x & (x - 1) do for a positive integer x?

Explanation

Subtracting 1 flips the lowest 1 and the zeros below it; AND removes that bit. So x & (x - 1) === 0 checks for a power of two, and repeating it counts the set bits.

Further reading

Problem with a question

Algorithms and Data Structures · Middle · question 62

Test yourself

Take the Algorithms and Data Structures · Middle quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz