Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Finding the next number with the same number of set bits #3556

Merged
merged 2 commits into from
Oct 2, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions bit_manipulation/Next_higher_no_with_same_no_of_set_bits/C++.cpp
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 bit_manipulation/Next_higher_no_with_same_no_of_set_bits/C.c
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;
}
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
Loading