From 11f9a22b8659307379ea8d684f09725d49e83f90 Mon Sep 17 00:00:00 2001 From: Saddam H Date: Mon, 29 Mar 2021 15:58:59 +0600 Subject: [PATCH] content: check if a number is a power of 2 (#196) * 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. * Update binary.md Co-authored-by: Yangshun Tay --- 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..c11dd1f3 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