-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #3556 from RoyCoding8/master
Finding the next number with the same number of set bits
- Loading branch information
Showing
3 changed files
with
54 additions
and
0 deletions.
There are no files selected for viewing
23 changes: 23 additions & 0 deletions
23
bit_manipulation/Next_higher_no_with_same_no_of_set_bits/C++.cpp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
// Next higher number with same number of set bits | ||
#include <bits/stdc++.h> | ||
using namespace std; | ||
#define ll long long | ||
|
||
ll fun(ll n){ | ||
ll ans=0,r1,r,next; | ||
if(n){ | ||
r1=n&(-n); | ||
next=n+r1; | ||
r=(n^next)/r1; | ||
r>>=2; | ||
ans=next|r; | ||
} | ||
return ans; | ||
} | ||
|
||
int main(){ | ||
ll n; | ||
cin>>n; | ||
cout<<fun(n)<<endl; | ||
return 0; | ||
} |
22 changes: 22 additions & 0 deletions
22
bit_manipulation/Next_higher_no_with_same_no_of_set_bits/C.c
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
// Next higher number with same number of set bits | ||
#include<stdio.h> | ||
#define ll long long | ||
|
||
ll fun(ll n){ | ||
ll ans=0,r1,r,next; | ||
if(n){ | ||
r1=n&(-n); | ||
next=n+r1; | ||
r=(n^next)/r1; | ||
r>>=2; | ||
ans=next|r; | ||
} | ||
return ans; | ||
} | ||
|
||
int main(){ | ||
ll n; | ||
scanf("%lld",&n); | ||
printf("%lld",fun(n)); | ||
return 0; | ||
} |
9 changes: 9 additions & 0 deletions
9
bit_manipulation/Next_higher_no_with_same_no_of_set_bits/Python.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
def fun(n): | ||
if n==0: | ||
return 0 | ||
r1 = n & (-n) | ||
next = n + r1 | ||
r = (n ^ next) / r1 | ||
r >>= 2 | ||
ans = next | r | ||
return ans |