'Is bitwise complement of (n-1) equals to (-n)
The following code prints the two odd occuring numbers in an array:
#include <iostream>
using namespace std;
int main(){
int n;
cin>>n;
int arr[n],x=0;
for(int i=0;i<n;i++){
cin>>arr[i];
x=x^arr[i];
}
x=(x&~(x-1));
int reso=0,rest=0;
for(int i=0;i<n;i++){
if(x&arr[i])
reso=reso^arr[i];
else
rest=rest^arr[i];
}
cout<<reso<<' '<<rest;
return 0;
}
I observed that ~(x-1)==(-x) in 2's complement hence I replaced the ~(x-1) with (-x) and wrote the following code, which worked fine :
#include <iostream>
using namespace std;
int main(){
int n;
cin>>n;
int arr[n],x=0;
for(int i=0;i<n;i++){
cin>>arr[i];
x=x^arr[i];
}
x=(x&(-x)); //changed expression
int reso=0,rest=0;
for(int i=0;i<n;i++){
if(x&arr[i])
reso=reso^arr[i];
else
rest=rest^arr[i];
}
cout<<reso<<' '<<rest;
return 0;
}
So I need help, is ~(x-1) is equal to (-x) in 2's complement or I am misconcluding here, kindly provide explanation ?
Solution 1:[1]
Taking the 1's complement of a d-1 digits number is the same as subtracting it from the number 111...1 (d-1) digits, which is 2^d-1.
E.g. with five bits numbers,
9d = 01001b; ~9d = 10110b = -16d + 6d = -10d
and
-9d = -16d + 6d = 11010b
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Yves Daoust |
