I was trying to make a program for the next largest number with the same no of 1 in its binary representation. The nxtlarge function isn’t working, but nxtsmall works.
#include
using namespace std;
int nxtsmall(int num){
int l;
l=num&1;
if(l==1){
cout<<(num-3)<<endl;
}
else { cout<<(num-1)<<endl;
}
}
int nxtlarge(int num){
int c=0, temp=num;
while(temp>0){
c++;
temp>>1;
};
int l[c]={0};
for(int i=0;i<c;i++){
l[i]=num&1;
}
for(int i=c;i>0;i–){
if(l[i]==1){
for(int j=i-1;j>0;j–){
if(l[j]==0){
num&(~(1<<(c-i)));
num|(1<<(c-j));
}
else continue;
}
}
}
for(int i=0;i<c;i++){
if(l[i]==1){
for(int j=i+1;j<c;j++){
if(l[j]==0){
num&(~(1<<(i)));
num|(1<<(j));
cout<<num<<endl;
}
else continue;
}
}
}
}
int main(){
int num;
cin>>num;
cout<<“smallest and largest”<<endl;
nxtsmall(num);
nxtlarge(num);
return 0;
}