Cracking The Coding Interview/Q 5.4

From Software Engineers Wiki
Jump to: navigation, search

Explain what the following code does: ((n & (n - 1)) == 0).

Answer

It basically checks whether n is power of 2. For 2^N, only one bit is 1. n-1 clears that bit, and sets any trailing least significant bits. For example,

  • 2^16 = 0x10000 = 0b100000000
  • 2^16 - 1 = 0x0ffff = 0b01111111
  • (2^16) & (2^16 - 1) = 0x10000 & 0x0ffff = 0
Personal tools
Namespaces

Variants
Actions
Navigation
Toolbox