Skip to content

Commit 22732c5

Browse files
committed
Add problem 3158: Find the XOR of Numbers Which Appear Twice
1 parent 7b2d36c commit 22732c5

File tree

3 files changed

+60
-0
lines changed

3 files changed

+60
-0
lines changed

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2111,6 +2111,7 @@ pub mod problem_3148_maximum_difference_score_in_a_grid;
21112111
pub mod problem_3151_special_array_i;
21122112
pub mod problem_3152_special_array_ii;
21132113
pub mod problem_3153_sum_of_digit_differences_of_all_pairs;
2114+
pub mod problem_3158_find_the_xor_of_numbers_which_appear_twice;
21142115
pub mod problem_3350_adjacent_increasing_subarrays_detection_ii;
21152116

21162117
#[cfg(test)]
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
pub struct Solution;
2+
3+
// ------------------------------------------------------ snip ------------------------------------------------------ //
4+
5+
impl Solution {
6+
pub fn duplicate_numbers_xor(nums: Vec<i32>) -> i32 {
7+
let nums = nums.into_iter().map(i32::cast_unsigned).collect::<Vec<_>>();
8+
let mut bits = 0_u64;
9+
10+
for &num in &nums {
11+
bits |= 1 << num;
12+
}
13+
14+
let mut xor = 0;
15+
16+
while bits != 0 {
17+
let num = bits.trailing_zeros();
18+
19+
xor ^= num;
20+
bits ^= 1 << num;
21+
}
22+
23+
nums.iter().fold(xor, |xor, &num| xor ^ num).cast_signed()
24+
}
25+
}
26+
27+
// ------------------------------------------------------ snip ------------------------------------------------------ //
28+
29+
impl super::Solution for Solution {
30+
fn duplicate_numbers_xor(nums: Vec<i32>) -> i32 {
31+
Self::duplicate_numbers_xor(nums)
32+
}
33+
}
34+
35+
#[cfg(test)]
36+
mod tests {
37+
#[test]
38+
fn test_solution() {
39+
super::super::tests::run::<super::Solution>();
40+
}
41+
}
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
pub mod iterative;
2+
3+
pub trait Solution {
4+
fn duplicate_numbers_xor(nums: Vec<i32>) -> i32;
5+
}
6+
7+
#[cfg(test)]
8+
mod tests {
9+
use super::Solution;
10+
11+
pub fn run<S: Solution>() {
12+
let test_cases = [(&[1, 2, 1, 3] as &[_], 1), (&[1, 2, 3], 0), (&[1, 2, 2, 1], 3)];
13+
14+
for (nums, expected) in test_cases {
15+
assert_eq!(S::duplicate_numbers_xor(nums.to_vec()), expected);
16+
}
17+
}
18+
}

0 commit comments

Comments
 (0)