Skip to content

Instantly share code, notes, and snippets.

@ThunderXu
Last active December 15, 2015 14:39
Show Gist options
  • Save ThunderXu/5276198 to your computer and use it in GitHub Desktop.
Save ThunderXu/5276198 to your computer and use it in GitHub Desktop.
Given a positive integer, print the next smallest and the next largest number that have the same number of 1 bits in their binary representation.
#include <iostream>
#include <bitset>
int GetNextLargest(int num);
int GetNextSmallest(int num);
int main()
{
int num;
std::cin>>num;
std::cout<<GetNextLargest(num)<<std::endl;
std::cout<<GetNextSmallest(num)<<std::endl;
}
int GetNextLargest(int num)
{
using namespace std;
bitset<32> btnum(num);
bitset<32> btres(num);
int highpos=-1;
int pos=0;
while(pos<31)
{
if(btres.test(pos)&&!btres.test(pos+1))
{
btres.set(pos+1);
btres.reset(pos);
highpos=pos;
break;
}
pos++;
}
if(highpos!=-1)
{
//count the number of 1 from 0 to pos
int count=0;
for(int i=0;i<highpos;i++)
{
if(btres.test(i))
{
count++;
}
}
//set 1s to rightmost
for(int i=0;i<highpos;i++)
{
if(count!=0)
{
btres.set(i);
count--;
}
else
{
btres.reset(i);
}
}
return (int)(btres.to_ulong());
}
}
int GetNextSmallest(int num)
{
using namespace std;
bitset<32> btnum(num);
bitset<32> btres(num);
int highpos=-1;
int pos=0;
while(pos<31)
{
if(btres.test(pos+1)&&!btres.test(pos))
{
btres.set(pos);
btres.reset(pos+1);
highpos=pos;
break;
}
pos++;
}
if(highpos!=-1)
{
//count the number of 1 from 0 to pos
int count=0;
for(int i=0;i<highpos;i++)
{
if(btres.test(i))
{
count++;
}
}
//set 1s to rightmost
for(int i=highpos-1;i>=0;i--)
{
if(count!=0)
{
btres.set(i);
count--;
}
else
{
btres.reset(i);
}
}
return (int)(btres.to_ulong());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment