vault backup: 2022-07-22 16:03:37
This commit is contained in:
parent
eb98bb77b6
commit
d01b45c5cd
|
@ -22,7 +22,8 @@ tag:#bit_manipulation
|
|||
|
||||
##### Links:
|
||||
- [Link to problem](https://leetcode.com/problems/single-number/)
|
||||
- [Learn about XOR]()
|
||||
- [Learn about XOR](https://en.wikipedia.org/wiki/Exclusive_or#Computer_science)
|
||||
- [Explanation](https://leetcode.com/problems/single-number/discuss/1772139/C%2B%2Bor-Explained-Everything-w-WHY-XOR-WORKSor-BRUTE-FORCE-TO-OPTIMIZEDor-STEP-BY-STEP-DRY-RUN)
|
||||
___
|
||||
### Problem
|
||||
|
||||
|
@ -59,5 +60,29 @@ You must implement a solution with a linear runtime complexity and use only co
|
|||
> This is a #bit_manipulation problem utilizing the XOR operator
|
||||
|
||||
|
||||
The XOR operator has some properties:
|
||||
|
||||
```
|
||||
a ^ a = 0;
|
||||
a ^ b ^ a = a ^ a ^ b = b;
|
||||
```
|
||||
|
||||
This can be used for our problem.
|
||||
|
||||
### Solution
|
||||
|
||||
```cpp
|
||||
class Solution {
|
||||
public:
|
||||
int singleNumber(vector<int> &nums) {
|
||||
// Using XOR operator
|
||||
int ans = 0;
|
||||
|
||||
for (int i : nums) {
|
||||
ans ^= i;
|
||||
}
|
||||
|
||||
return ans;
|
||||
}
|
||||
};
|
||||
```
|
Loading…
Reference in a new issue