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

$
0
0

Kotlin:

fun isPowerOfTwo(n: Int): Boolean {    return (n > 0) && (n.and(n-1) == 0)}

or

fun isPowerOfTwo(n: Int): Boolean {    if (n == 0) return false    return (n and (n - 1).inv()) == n}

inv inverts the bits in this value.


Note:
log2 solution doesn't work for large numbers, like 536870912 ->

import kotlin.math.truncateimport kotlin.math.log2fun isPowerOfTwo(n: Int): Boolean {    return (n > 0) && (log2(n.toDouble())) == truncate(log2(n.toDouble()))}

Viewing all articles
Browse latest Browse all 38

Latest Images

Trending Articles



Latest Images

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