Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 66c6336

Browse files
Update check_if_power_of_4.cpp
fixed decimal to binary conversions in notes, and improved formatting. Also a suggestion on a slightly more straightforward solution.
1 parent e6c138b commit 66c6336

File tree

1 file changed

+8
-6
lines changed

1 file changed

+8
-6
lines changed

‎bit_manipulation/check_if_power_of_4.cpp

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,15 +4,15 @@
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
*/
@@ -24,6 +24,8 @@
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()
@@ -33,10 +35,10 @@
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+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /