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.
int decrement(int x)
{
return (~(-x));
}
Read full article from Add 1 to a given number | GeeksforGeeks
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
We know that the negative number is represented in 2′s complement form on most of the architectures. We have the following lemma hold for 2′s complement representation of signed numbers.
We know that the negative number is represented in 2′s complement form on most of the architectures. We have the following lemma hold for 2′s complement representation of signed numbers.
~x = -(x+1) [ ~ is for bitwise complement ]
To get (x + 1) apply negation once again. So, the final expression becomes (-(~x)).
int addOne( int x) { return (-(~x)); } |
{
return (~(-x));
}
Read full article from Add 1 to a given number | GeeksforGeeks
No comments:
Post a Comment