Skip to content

Commit

Permalink
Merge pull request #3556 from RoyCoding8/master
Browse files Browse the repository at this point in the history
Finding the next number with the same number of set bits
  • Loading branch information
ZoranPandovski authored Oct 2, 2023
2 parents 7dad9d0 + de74291 commit 90f3677
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 0 deletions.
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

0 comments on commit 90f3677

Please sign in to comment.