|
| 1 | +/// Finds the unique number in a slice where every other element appears twice. |
| 2 | +/// |
| 3 | +/// This function uses the XOR bitwise operation. Since XOR has the property that |
| 4 | +/// `a ^ a = 0` and `a ^ 0 = a`, all paired numbers cancel out, leaving only the |
| 5 | +/// unique number. |
| 6 | +/// |
| 7 | +/// # Arguments |
| 8 | +/// |
| 9 | +/// * `arr` - A slice of integers where all elements except one appear exactly twice |
| 10 | +/// |
| 11 | +/// # Returns |
| 12 | +/// |
| 13 | +/// * `Ok(i32)` - The unique number that appears only once |
| 14 | +/// * `Err(String)` - An error message if the input is empty |
| 15 | +/// |
| 16 | +/// # Examples |
| 17 | +/// |
| 18 | +/// ``` |
| 19 | +/// # use the_algorithms_rust::bit_manipulation::find_unique_number; |
| 20 | +/// assert_eq!(find_unique_number(&[1, 1, 2, 2, 3]).unwrap(), 3); |
| 21 | +/// assert_eq!(find_unique_number(&[4, 5, 4, 6, 6]).unwrap(), 5); |
| 22 | +/// assert_eq!(find_unique_number(&[7]).unwrap(), 7); |
| 23 | +/// assert_eq!(find_unique_number(&[10, 20, 10]).unwrap(), 20); |
| 24 | +/// assert!(find_unique_number(&[]).is_err()); |
| 25 | +/// ``` |
| 26 | +pub fn find_unique_number(arr: &[i32]) -> Result<i32, String> { |
| 27 | + if arr.is_empty() { |
| 28 | + return Err("input list must not be empty".to_string()); |
| 29 | + } |
| 30 | + |
| 31 | + let result = arr.iter().fold(0, |acc, &num| acc ^ num); |
| 32 | + Ok(result) |
| 33 | +} |
| 34 | + |
| 35 | +#[cfg(test)] |
| 36 | +mod tests { |
| 37 | + use super::*; |
| 38 | + |
| 39 | + #[test] |
| 40 | + fn test_basic_case() { |
| 41 | + assert_eq!(find_unique_number(&[1, 1, 2, 2, 3]).unwrap(), 3); |
| 42 | + } |
| 43 | + |
| 44 | + #[test] |
| 45 | + fn test_different_order() { |
| 46 | + assert_eq!(find_unique_number(&[4, 5, 4, 6, 6]).unwrap(), 5); |
| 47 | + } |
| 48 | + |
| 49 | + #[test] |
| 50 | + fn test_single_element() { |
| 51 | + assert_eq!(find_unique_number(&[7]).unwrap(), 7); |
| 52 | + } |
| 53 | + |
| 54 | + #[test] |
| 55 | + fn test_three_elements() { |
| 56 | + assert_eq!(find_unique_number(&[10, 20, 10]).unwrap(), 20); |
| 57 | + } |
| 58 | + |
| 59 | + #[test] |
| 60 | + fn test_empty_array() { |
| 61 | + assert!(find_unique_number(&[]).is_err()); |
| 62 | + assert_eq!( |
| 63 | + find_unique_number(&[]).unwrap_err(), |
| 64 | + "input list must not be empty" |
| 65 | + ); |
| 66 | + } |
| 67 | + |
| 68 | + #[test] |
| 69 | + fn test_negative_numbers() { |
| 70 | + assert_eq!(find_unique_number(&[-1, -1, -2, -2, -3]).unwrap(), -3); |
| 71 | + } |
| 72 | + |
| 73 | + #[test] |
| 74 | + fn test_large_numbers() { |
| 75 | + assert_eq!( |
| 76 | + find_unique_number(&[1000, 2000, 1000, 3000, 3000]).unwrap(), |
| 77 | + 2000 |
| 78 | + ); |
| 79 | + } |
| 80 | + |
| 81 | + #[test] |
| 82 | + fn test_zero() { |
| 83 | + assert_eq!(find_unique_number(&[0, 1, 1]).unwrap(), 0); |
| 84 | + } |
| 85 | +} |
0 commit comments