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 rhodan for How to check if a number is a power of 2

$
0
0

Improving the answer of @user134548, without bits arithmetic:

public static bool IsPowerOfTwo(ulong n){    if (n % 2 != 0) return false;  // is odd (can't be power of 2)    double exp = Math.Log(n, 2);    if (exp != Math.Floor(exp)) return false;  // if exp is not integer, n can't be power    return Math.Pow(2, exp) == n;}

This works fine for:

IsPowerOfTwo(9223372036854775809)

Viewing all articles
Browse latest Browse all 38

Trending Articles



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