I had been studying the algorithm for finding lonely integers in an array, and here is the implementation:
int arr[] = {10, 20, 30, 5, 20, 10, 30}; int LonelyInteger = 0; for(int i=0; i< 7; i++) { LonelyInteger = LonelyInteger ^ arr[i]; }
The result is 5
.
My question is - supposedly the integers (getting generated by the XOR
operation) are too large due to this operation:
LonelyInteger ^ arr[i]
Which leads to a potentially large integer which cannot be represented by the datatype say int
in this case. My questions are:
XOR
will generate such a large integer value that cannot be stored in the int
type?XOR is a bitwise operation. It does not generate integers, it generates bit patterns. The result is logically either a trap representation, or a non-trap representation of a value. It's not possible to get a "too large" result because the "too large" result would not be representable.
The XOR works by setting the bits which are set in either of one of the given numbers (0 ^ 1 = 1, 1 ^ 0 = 1) and finally taking out the common bits present in both numbers (1 ^ 1 = 0) .
Explanation: There are only 2 pairs whose Bitwise XOR is greater than both the elements in the pair: 1) (2, 4): Bitwise XOR = 2 ^ 4 = 6, which is greater than both 2 and 4. 2) (4, 3): Bitwise XOR = 4 ^ 3 = 7, which is greater than both 4 and 3.
XOR
will never go out of bounds because it combines bits and doesn't create new bits where no bits were set before.
The result 5
is correct. Look at the binary representation of your value and the XOR
result
10 00001010 20 00010100 30 00011110 5 00000101 20 00010100 10 00001010 30 00011110 -------------- 00000101 => 5
An easy help for calculating a result of many XOR
ed values is: The result will have a bit set where an odd number of bits are combined, no bit set for even number of bits.
If it is not possible that this can happen then is there a proof for this?
XOR
is equivalent to addition without carry on the individual bits. When you add bits without carry, no overflow can happen and so the int
value can't go out of bounds.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With