Friday, September 14, 2012

******Add 1 to a given number**********



Write a program to add one to a given number. You are not allowed to use operators like ‘+’, ‘-’, ‘*’, ‘/’, ‘++’, ‘–’ …etc.

Examples:
Input: 12
Output: 13

Input: 6
Output: 7

Yes, you guessed it right, we can use bitwise operators to achieve this. Following are different methods to achieve same using bitwise operators.

Method 1
To add 1 to a number x (say 0011000111), we need to flip all the bits after the rightmost 0 bit (we get 0011000000). Finally, flip the rightmost 0 bit also (we get 0011001000) and we are done.

#include<stdio.h>

int addOne(int x)
{
int m = 1;

/* Flip all the set bits until we find a 0 */
while( x & m )
{
x = x^m;
m <<= 1;
}

/* flip the rightmost 0 bit */
x = x^m;
return x;
}

/* Driver program to test above functions*/
int main()
{
printf("%d", addOne(13));
getchar();
return 0;
}

No comments:

Post a Comment