next higher number having equal number of 1's

Input a number and then find the next higher number such that for both the number (inputted and the next higher number) in binary representation contains equal number of ones. Example: Input:3(0000000000000011) Ouput:5(0000000000000101)

Comments

  1. unsigned int snoob(unsigned int a)
    {
    unsigned int smallest, ripples, ones;
    smallest = a & -a;
    ripples = a + smallest;
    ones = a ^ ripples;
    ones = (ones >> 2)/smallest;
    return ripples | ones;
    }
    main()
    {
    int num;
    num = 3;
    printf( " Next higher number %d",snoob(num));
    getch();
    }

    ReplyDelete
  2. @priyaranjan cud u please xplain the logic???

    ReplyDelete

Post a Comment

Popular posts from this blog