Power of 2
Learn Power of 2 (Bit Manipulation, Data Structures & Algorithms) with worked examples, diagrams and interview questions. Free on JavaSchoolLab.
Checking if a Number is a Power of 2, in O(1) A power of 2 has EXACTLY ONE set bit (e.g. 8 = 1000, 16 = 10000). Recall num & (num - 1) clears the lowest set bit - if num had only ONE set bit to begin with, clearing it leaves 0. So: num > 0 && (num & (num - 1)) == 0 .