top button
Flag Notify
    Connect to us
      Facebook Login
      Site Registration

Facebook Login
Site Registration

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

+3 votes
81 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'.
Similar Questions
Contact Us
+91 9880187415
sales@queryhome.net
support@queryhome.net
#280, 3rd floor, 5th Main
6th Sector, HSR Layout
Bangalore-560102
Karnataka INDIA.
QUERY HOME
...