Write a program to add one to a given number. You are not allowed to use operators like ‘+’, ‘-’, ‘*’, ‘/’, ‘++’, ‘–’ …etc.
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.
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.
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;
}
Method 2
Say, x is numerical value of a number, then
~x = -(x+1) [ ~ is for bitwise complement ]
(x + 1) is due to addition of 1 in 2′s complement conversion
To get (x + 1) apply negation once again. So, the final expression becomes (-(~x)).
int
addOne(
int
x)
{
return
(-(~x));
}
int decrement(int x)
{
return (~(-x));
}
Read full article from Add 1 to a given number | GeeksforGeeks