![]() |
VOOZH | about |
The task is to Increment a number without using ++ and + operators.
Examples:
Input : 3 Output : 4 Input : 9 Output : 10
The idea is based on the fact that the negative numbers are stored using 2's complement form. 2's complement form is obtained by inverting bits and then adding one. So if we invert all bits of given number and apply negative sign, we get the number plus 1.
4
It also works for characters.
Example:
Input : a Output : b Input : o Output : p
Time Complexity: O(1)
Auxiliary Space: O(1)
b
Time Complexity: O(1)
Auxiliary Space: O(1)
Similar to the approach of using complement, we can use double negation to increment a number, as a -(-1) is equivalent to a + 1.
4
Time Complexity: O(1)
Auxiliary Space: O(1)