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.

[ad type=”banner”]

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.

 

[pastacode lang=”c” manual=”%23include%3Cstdio.h%3E%0A%20%0Aint%20addOne(int%20x)%0A%7B%0A%20%20int%20m%20%3D%201%3B%0A%20%0A%20%20%2F*%20Flip%20all%20the%20set%20bits%20until%20we%20find%20a%200%20*%2F%0A%20%20while(%20x%20%26%20m%20)%0A%20%20%7B%0A%20%20%20%20x%20%3D%20x%5Em%3B%0A%20%20%20%20m%20%3C%3C%3D%201%3B%0A%20%20%7D%0A%20%0A%20%20%2F*%20flip%20the%20rightmost%200%20bit%20*%2F%0A%20%20x%20%3D%20x%5Em%3B%0A%20%20return%20x%3B%0A%7D%0A%20%0A%2F*%20Driver%20program%20to%20test%20above%20functions*%2F%0Aint%20main()%0A%7B%0A%20%20printf(%22%25d%22%2C%20addOne(13))%3B%0A%20%20getchar()%3B%0A%20%20return%200%3B%0A%7D” message=”c” highlight=”” provider=”manual”/] [ad type=”banner”]

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.

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)).

 

[pastacode lang=”c” manual=”int%20addOne(int%20x)%0A%7B%0A%20%20%20return%20(-(~x))%3B%0A%7D%0A%20%0A%2F*%20Driver%20program%20to%20test%20above%20functions*%2F%0Aint%20main()%0A%7B%0A%20%20printf(%22%25d%22%2C%20addOne(13))%3B%0A%20%20getchar()%3B%0A%20%20return%200%3B%0A%7D” message=”c” highlight=”” provider=”manual”/]

Example, assume the machine word length is one *nibble* for simplicity.
And x = 2 (0010),
~x = ~2 = 1101 (13 numerical)
-~x = -1101
Interpreting bits 1101 in 2’s complement form yields numerical value as -(2^4 – 13) = -3. Applying ‘-‘ on the result leaves 3. Same analogy holds for decrement. See this comment for implementation of decrement.
Note that this method works only if the numbers are stored in 2’s complement form.

[ad type=”banner”]