top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Write a program to replace the right most bit '0' with bit '1' in a number ?

+3 votes
686 views
Write a program to replace the right most bit '0' with bit '1' in a number ?
posted Jun 7, 2015 by Harshita

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

2 Answers

+2 votes
 
Best answer

Tested code -

#include<stdio.h>
main()
{
    int num;
    printf("Enter a number\n");
    scanf("%d",&num);

    num=(num+1)|num;   
    printf("%d\n", num);
}
answer Jun 7, 2015 by Salil Agrawal
Simple and fast, and the most important it will work with any machine i.e 16 bit, 32 bit or 64 bit.
0 votes
  #include<stdio.h>
    main()
    {
    int num,i;
    printf("Enter a number\n");
    scanf("%d",&num);
    num=num|1;   
        for(i=31;i>=0;i--)
        {
            if(num&1<<i)
                printf("1");
            else
                printf("0");
            if(i%4==0)
                printf("\t");
        }
     printf("\n");
     }
answer Jun 7, 2015 by Chirag Gangdev
Solution looks to be wrong and does not solve the original problem.
this code will replace last bit from 0 to 1.
Ex : num=10, binary representation is "0000 1010"
after applying this code it will be "0000 1011"
Check for 7, I have provided more simpler version check it
Sir, If it is 7 then also this code will work,
because the question is if last bit is '0' then only we have to convert it to '1'.
...