for next larger number
check for 1st bit set
x = n&~(n-1)
e.g. n = 10100 = 20
n -1 = 10011
x = 10100 & 01100 = 100
for next larger number check for 1st 0 and set the bit
thus y = ~x
n = y & ~(y-1)
x |= n
x = 10101 = 21
y = 01010 = 10
y-1 = 01001 = 9
n = 1010 & 110 = 0010
x = 10111 = 23
now this has one bit more
so to turn this off
again
x = x & ~( x & ~(x-1))
i.e. 10111 & ~(10111 & 01001) = 10111 & 11110 = 10110 = 22
do similarly for small number
On Oct 16, 2:31 pm, rajul jain <[email protected]> wrote:
> I have read this question earlier
> the algo is like this
> 1)Traverse from right to left , once we passed 1, turn on next 0 and also
> turn off the one that's just to right side of
> that.
> example xxx11011 become xx101011
> 2) for making number small just rearrange all 1's to be as right as
> possible.
> xx101011 become xx100111
> similary you can get larger number by rearrange all 1's to left .
>
> On Wed, Mar 2, 2011 at 1:20 AM, bittu <[email protected]> wrote:
> > Given an integer, print the next smallest and next largest number that
> > have the same number of 1 bits in their binary representation.
>
> > Example for n=12
> > next smallest with same no. of set bit is 17 but to found next
> > largest ..we have to be careful ..
>
> > let c others ..??
>
> > Thanks & Regards
> > Shashank
>
> > --
> > 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.
--
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.