Problem Statement
Given an integer x
, add 1
to it using bit manipulation techniques (without using the +
operator).
Different Approach
1️⃣ Two's Complement
Using Bit Manipulation:
We know that to get negative of a number, invert its bits and add 1 to it. (negative numbers are stored in 2's complement)
#include <iostream>
using namespace std;
int main()
{
int x = 4;
cout << x << " + " << 1 << " is " << -~x << endl;
x = -5;
cout << x << " + " << 1 << " is " << -~x << endl;
x = 0;
cout << x << " + " << 1 << " is " << -~x << endl;
return 0;
}
// Output
4 + 1 is 5
-5 + 1 is -4
0 + 1 is 1