Saturday, 19 July 2014

Find largest number obtained by changing the bits of a given number

For Example : 5 is represented in binary as 101 but the largest number can be 6(110)
Input   :A number n
Output: Largest number


#include <iostream>
#include <cmath>
using namespace std;
int FindLargest ( int n )
{
    int one=0,t=0,final=0;
    while ( n!=0 )
    {
        if ( n&1==1 )
        {
            one++;
            t++;
            n=n>>1;
        }
        else
        {
            t++;
            n=n>>1;
        }
    }
    for ( int i=t-1; i>=t-one; i-- )
    {
        final+=pow ( 2.0,i );
    }
    return final;
}
int main()
{
    int n;
    cin>>n;

    cout<<FindLargest ( n );

    getchar();

}


Please comment if you find anything incorrect.

No comments:

Post a Comment