#include<iostream>
typedef unsigned int ui;
ui nextsmallest( ui n)
{
ui x;
int ctr=-1;
x= (n&~(n-1)); // the lowest bit set in 'n'
while( x&n) // finds the number of consecutive bits set from the
lowest one
{
x<<=1;
ctr++;
}
n^=x;
n&=(~(x-1));
x=1;
while( ctr--)
{
n^=x;
x<<=1;
}
return n;
}
ui nextlargest( ui n)
{
ui y=0,x=0,z=1;
while( y<32)
{
if( z&n)
++x;
z<<=1;
++y;
}
n=0;
y= 1<<31;
while( x--)
{
n^=y;
y>>=1;
}
return n;
}
int main()
{
ui n;
scanf("%u",&n);
printf("Next smallest : %u\n",nextsmallest(n));
printf("Next largest : %u\n",nextlargest(n));
//system("PAUSE");
}
I hope this would suffice. Ofcourse, this piece of code fails for all
numbers having all their 1's in consecutively highest locations and you
ought to be knowing why it fails.
--
Himanshu Sachdeva
--
You received this message because you are subscribed to the Google Groups
"Algorithm Geeks" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/algogeeks?hl=en.