Skip to content

Commit 20a182c

Browse files
committed
Day 38 addition without arithmetic operators
1 parent 34c3797 commit 20a182c

File tree

2 files changed

+48
-3
lines changed

2 files changed

+48
-3
lines changed

README.md

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,9 @@
44

55
| Current Status| Stats |
66
| :------------: | :----------: |
7-
| Total Problems | 57 |
8-
| Current Streak | 37 |
9-
| Longest Streak | 37 ( August 17, 2015 - September 22, 2015 ) |
7+
| Total Problems | 58 |
8+
| Current Streak | 38 |
9+
| Longest Streak | 38 ( August 17, 2015 - September 23, 2015 ) |
1010

1111
</center>
1212

@@ -61,6 +61,7 @@ Include contains single header implementation of data structures and some algori
6161
| Given two integers, determine if their sum would be interger overflow.| [integerOverflow.cpp](bit_manipulation/integerOverflow.cpp)|
6262
| How many bit flip operation would require to convert number A to B. | [countNumberOfBitFlips.cpp](bit_manipulation/countNumberOfBitFlips.cpp)|
6363
| Given a number x and two positions (from right side) in binary representation of x, write a function that swaps n right bits at given two positions and returns the result. It is also given that the two sets of bits do not overlap.|[swapSetOfBits.cpp](bit_manipulation/swapSetOfBits.cpp)|
64+
| Add two numbers without using any arithmetic operators | [addition_without_operators.cpp](bit_manipulation/addition_without_operators.cpp)
6465

6566
### Cracking the coding interview problems
6667
| Problem | Solution |
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
/**
2+
* Addtion of two numbers without using any arithmatic operators.
3+
*/
4+
#include <iostream>
5+
6+
int sum( int x, int y ) {
7+
int carry = 0;
8+
while( y != 0 ) {
9+
10+
//if x and y don't have same bits at same position, XOR of x and y
11+
//gives us sum of x and y at those positions.
12+
// bits wont change at positions containing same bits, however,
13+
// we have to incorporate carry bits. AND of x and y gives all carry bits.
14+
// carry will be added from position 1 (not 0), so we need to shift carry
15+
// by 1.
16+
carry = x & y;
17+
x = x ^ y;
18+
y = carry << 1;
19+
}
20+
return x;
21+
}
22+
23+
//recursive version
24+
int sum2( int x, int y ) {
25+
if ( y == 0 ) {
26+
return x;
27+
}
28+
return sum2( x ^ y, (x & y) << 1);
29+
}
30+
31+
int main()
32+
{
33+
int x , y;
34+
std::cout << "Addition of two numbers without using arithmatic operators:\n";
35+
std::cout << "Enter num 1 :" ;
36+
std::cin >> x;
37+
std::cout << "Enter num 2 :" ;
38+
std::cin >> y;
39+
std::cout << "Iterative version - Addition of " << x << " and " << y
40+
<< " is " << sum(x, y) << std::endl;
41+
std::cout << "Recursive version - Addition of " << x << " and " << y
42+
<< " is " << sum2(x, y) << std::endl;
43+
return 0;
44+
}

0 commit comments

Comments
 (0)