forked from 7oSkaaa/LeetCode_DailyChallenge_2023
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create 04- Single Number II (Ahmed Hossam).cpp
- Loading branch information
Showing
1 changed file
with
27 additions
and
0 deletions.
There are no files selected for viewing
27 changes: 27 additions & 0 deletions
27
07- July/04- Single Number II/04- Single Number II (Ahmed Hossam).cpp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
// Author: Ahmed Hossam | ||
|
||
class Solution { | ||
public: | ||
int singleNumber(vector<int>& nums) { | ||
// Variable to store the single number | ||
int single = 0; | ||
|
||
// Loop through each bit position from 0 to 31 | ||
for(int bits = 0, curr_bit = 0; bits < 32; bits++, curr_bit = 0) { | ||
// Iterate over each element in the vector | ||
for(auto& i : nums) { | ||
// Check if the current bit is set in the element | ||
if(i & (1ll << bits)) | ||
curr_bit++; | ||
} | ||
|
||
// Check if the count of the current bit is not a multiple of 3 | ||
if(curr_bit % 3 == 1) | ||
// Set the corresponding bit in the single variable | ||
single |= (1 << bits); | ||
} | ||
|
||
// Return the single number | ||
return single; | ||
} | ||
}; |