LeetCode Entry

231. Power of Two

19.02.2024 easy 2024 kotlin rust

Is number 2^x?

231. Power of Two easy blog post substack youtube image.png

Join me on Telegram

https://t.me/leetcode_daily_unstoppable/511

Problem TLDR

Is number 2^x?

Intuition

Power of two number has just one bit on: 2 -> 10, 4 -> 100, 8 -> 1000. There is a known bit trick to turn off a single rightmost bit: n & (n - 1).

Approach

  • careful with the negative numbers and zero

Complexity

  • Time complexity: \(O(1)\)

  • Space complexity: \(O(1)\)

Code


    fun isPowerOfTwo(n: Int) =
      n > 0 && n and (n - 1) == 0


    pub fn is_power_of_two(n: i32) -> bool {
      n > 0 && n & (n - 1) == 0
    }