Quantcast
Channel: How to check if a number is a power of 2 - Stack Overflow
Viewing all articles
Browse latest Browse all 38

Answer by Khaled.K for How to check if a number is a power of 2

$
0
0

Example

0000 0001    Yes0001 0001    No

Algorithm

  1. Using a bit mask, divide NUM the variable in binary

  2. IF R > 0 AND L > 0: Return FALSE

  3. Otherwise, NUM becomes the one that is non-zero

  4. IF NUM = 1: Return TRUE

  5. Otherwise, go to Step 1

Complexity

Time ~ O(log(d)) where d is number of binary digits


Viewing all articles
Browse latest Browse all 38

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>