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 2d98fa2

Browse files
Merge pull request #234 from mahek5/newcode
Added a Bitwise operation program
2 parents 08a4c9c + 082f92d commit 2d98fa2

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
#include <iostream>
2+
using namespace std;
3+
4+
int main() {
5+
long N;
6+
cin>>N;
7+
largest_power(N);}
8+
void largest_power(long N)
9+
{
10+
//changing all right side bits to 1.
11+
N = N| (N>>1);
12+
N = N| (N>>2);
13+
N = N| (N>>4);
14+
N = N| (N>>8);
15+
16+
17+
//as now the number is 2 * x-1, where x is required answer, so adding 1 and dividing it by
18+
2.
19+
printf((N+1)>>1;
20+
21+
}
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
# Finding the largest power of 2 (most significant bit in binary form), which is less than or
2+
equal to the given number N.
3+
4+
Let’s say binary form of a N is {1111}base2 which is equal to 15.
5+
15 = 2^4-1, where 4 is the number of bits in N.
6+
7+
This property can be used to find the largest power of 2 less than or equal to N. How?
8+
If we somehow, change all the bits which are at right side of the most significant bit of N to 1, then the number will become x + (x-1) = 2 * x -1 , where x is the required answer.
9+
Example:
10+
Let’s say N = 21 = {10101}, here most significant bit is the 4th one. (counting from 0th digit) and so the answer should be 16.
11+
So lets change all the right side bits of the most significant bit to 1. Now the number changes to
12+
{11111} = 31 = 2 * 16 -1 = Y (let’s say).
13+
Now the required answer is (Y+1)>>1 or (Y+1)/2.

0 commit comments

Comments
(0)

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