Quantcast
Viewing latest article 30
Browse Latest Browse All 38

Answer by Dr.jacky for How to check if a number is a power of 2

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 latest article 30
Browse Latest Browse All 38

Trending Articles