File tree Expand file tree Collapse file tree 1 file changed +8
-6
lines changed Expand file tree Collapse file tree 1 file changed +8
-6
lines changed Original file line number Diff line number Diff line change 44 * Approach: If a value is power of 4, it has to be power of 2 and
55 * it will have set bits at even position (as the number is power of 2, it will have
66 * only one set bit.) For example:
7- * 4 (10 )
8- * 16 (10000 )
9- * 64 (1000000 )
7+ * 4 (0100 )
8+ * 16 (0001 0000 )
9+ * 64 (0100 0000 )
1010 * If a number is power of 2 then it would have only one set bit and that set
1111 * bit would be reset by the expression (n & (n-1)), thus if (n & (n-1)) == 0,
1212 * means n is power of 2.
1313 * Now, since we have one set bit and if it is at even position it would be
1414 * power of 4, to check if set bit is at even position, we should AND it with
15- * expression 10101010101010101010101010101010 i.e. 0xAAAAAAAA. Notice we have
15+ * expression 1010 1010 1010 1010 1010 1010 1010 1010 i.e. 0xAAAAAAAA. Notice we have
1616 * set bits at all odd positions (it is 0 indexed), thus if expression
1717 * (n & 0xAAAAAAAA) == 0, then we have that set bit at even position.
1818 */
2424 // The number should be power of 2, and should have set bit at even position
2525 //
2626 return (n && !(n & (n-1 )) && !(n & 0xAAAAAAAA ));
27+ // note an alternative that avoids the last negation could be
28+ // return (n && !(n & (n-1)) && (n & 0x55555555));
2729 }
2830
2931 int main ()
3335 std::cin >> n;
3436 if (isPowerOf4 (n))
3537 {
36- std::cout << n << " is power of 4.\n " ;
38+ std::cout << n << " is a power of 4.\n " ;
3739 }
3840 else
3941 {
4042 std::cout << n << " is not a power of 4.\n " ;
4143 }
42- }
44+ }
You can’t perform that action at this time.
0 commit comments