forked from mandliya/algorithms_and_data_structures
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaddBin.cpp
More file actions
42 lines (37 loc) · 880 Bytes
/
addBin.cpp
File metadata and controls
42 lines (37 loc) · 880 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/*
* Add two binary numbers represented as string.
*
*/
#include <iostream>
std::string addBinary(std::string & string1, std::string & string2){
int temp1=0, temp2=0;
int i=0;
std::string temp_string;
for(i; i<string1.size(); ++i){
temp1 |= ((string1[i] - '0') << (string1.size() - i - 1));
}
for(i=0; i<string2.size(); ++i){
temp2 |= ((string2[i] - '0') << (string2.size() - i - 1));
}
temp1 += temp2;
int count = string1.size();
for(i=0; i<count+1; ++i){
if(temp1 & (1<<count-i) && temp1 < (1<<count-i)){
break;
}
else if(temp1 & (1<<count-i)){
temp_string.append("1");
}
else{
temp_string.append("0");
}
}
return temp_string;
}
int main()
{
std::string str1("1010");
std::string str2("1011");
std::cout << "Addition of " << str1 << " and " << str2 << " is :" << addBinary(str1, str2) << std::endl;
return 0;
}