|
| 1 | +/** |
| 2 | + * This algorithm demonstrates how to add two integers without using the + operator |
| 3 | + * but instead relying on bitwise operations, like bitwise XOR and AND, to simulate |
| 4 | + * the addition. It leverages bit manipulation to compute the sum efficiently. |
| 5 | + */ |
| 6 | + |
| 7 | +pub fn add_two_integers(a: i32, b: i32) -> i32 { |
| 8 | + let mut a = a; |
| 9 | + let mut b = b; |
| 10 | + let mut carry; |
| 11 | + let mut sum; |
| 12 | + |
| 13 | + // Iterate until there is no carry left |
| 14 | + while b != 0 { |
| 15 | + sum = a ^ b; // XOR operation to find the sum without carry |
| 16 | + carry = (a & b) << 1; // AND operation to find the carry, shifted left by 1 |
| 17 | + a = sum; |
| 18 | + b = carry; |
| 19 | + } |
| 20 | + |
| 21 | + a |
| 22 | +} |
| 23 | + |
| 24 | +#[cfg(test)] |
| 25 | +mod tests { |
| 26 | + use super::add_two_integers; |
| 27 | + |
| 28 | + #[test] |
| 29 | + fn test_add_two_integers_positive() { |
| 30 | + assert_eq!(add_two_integers(3, 5), 8); |
| 31 | + assert_eq!(add_two_integers(100, 200), 300); |
| 32 | + assert_eq!(add_two_integers(65535, 1), 65536); |
| 33 | + } |
| 34 | + |
| 35 | + #[test] |
| 36 | + fn test_add_two_integers_negative() { |
| 37 | + assert_eq!(add_two_integers(-10, 6), -4); |
| 38 | + assert_eq!(add_two_integers(-50, -30), -80); |
| 39 | + assert_eq!(add_two_integers(-1, -1), -2); |
| 40 | + } |
| 41 | + |
| 42 | + #[test] |
| 43 | + fn test_add_two_integers_zero() { |
| 44 | + assert_eq!(add_two_integers(0, 0), 0); |
| 45 | + assert_eq!(add_two_integers(0, 42), 42); |
| 46 | + assert_eq!(add_two_integers(0, -42), -42); |
| 47 | + } |
| 48 | +} |
0 commit comments