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

81 views
Write a program to replace the right most bit '0' with bit '1' in a number ? posted Jun 7, 2015

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
Simple and fast, and the most important it will work with any machine i.e 16 bit, 32 bit or 64 bit.
``````  #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
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'.
Similar Questions

Using fprintf() print a single floating point number right-justified in a field of 20 spaces, no leading zeros, and 4 decimal places. The destination should be stderr and the variable is called num.