From b00fd2b52688a9bec68f649b659ffe4352805bc9 Mon Sep 17 00:00:00 2001 From: Saddam H Date: Thu, 25 Feb 2021 20:27:48 +0600 Subject: [PATCH] Check if a number is a power of 2 This representation may be easier to understand for some people. If a number is power of two then `AND` operation between the number and its complement will result into the same number. --- contents/algorithms/binary.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/contents/algorithms/binary.md b/contents/algorithms/binary.md index 741d8aa3..81d71154 100644 --- a/contents/algorithms/binary.md +++ b/contents/algorithms/binary.md @@ -17,7 +17,7 @@ Some helpful utility snippets: - Set kth bit: `num |= (1 << k)`. - Turn off kth bit: `num &= ~(1 << k)`. - Toggle the kth bit: `num ^= (1 << k)`. -- To check if a number is a power of 2, `num & num - 1 == 0`. +- To check if a number is a power of 2, `num & num - 1 == 0` or `num & (-num) == num`. ## Corner cases