Math Fundamentals18 sections · 814 units
Open in Course

Problem - Power of Two

LeetCode 231

Given an integer nn, return true if nn is a power of two. Otherwise, return false. An integer is a power of two if there exists an integer xx such that n=2xn = 2^x.

Examples: 11 (which is 202^0), 22, 44, 88, 1616 are powers of two. 33, 55, 66, 77 are not. What property do powers of two have in binary?

Look at the binary: 1=11 = 1, 2=102 = 10, 4=1004 = 100, 8=10008 = 1000, 16=1000016 = 10000. Every power of two has exactly one 1 bit. Non-powers have multiple 1 bits. How can you check for exactly one 1 bit?