Skip to content

Commit 173d856

Browse files
authored
Add sum of two integers using bit manipulation (#577)
1 parent 1050cb8 commit 173d856

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

src/bit_manipulation/mod.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
mod counting_bits;
22
mod highest_set_bit;
3+
mod sum_of_two_integers;
34

45
pub use counting_bits::count_set_bits;
56
pub use highest_set_bit::find_highest_set_bit;
7+
pub use sum_of_two_integers::add_two_integers;
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
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

Comments
 (0)