-
Notifications
You must be signed in to change notification settings - Fork 0
/
Addition of binary number.txt
93 lines (59 loc) · 1.6 KB
/
Addition of binary number.txt
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
Given two binary strings a and b, return their sum as a binary string.
Example 1:
Input: a = "11", b = "1"
Output: "100"
Example 2:
Input: a = "1010", b = "1011"
Output: "10101"
Constraints:
1 <= a.length, b.length <= 104
a and b consist only of '0' or '1' characters.
Each string does not contain leading zeros except for the zero itself.
Solution
string addBinary(string a, string b)
{
string result = "";
int s = 0 ;
int i = a.size() - 1, j = b.size() - 1;
while (i >= 0 || j >= 0 || s == 1)
{
// Comput sum of last digits and carry
s += ((i >= 0)? a[i] - '0': 0);
s += ((j >= 0)? b[j] - '0': 0);
// If current digit sum is 1 or 3, add 1 to result
result = char(s % 2 + '0') + result;
// Compute carry
s /= 2;
// Move to next digits
i--; j--;
}
return result;
}
// Driver program
int main()
{
string a = "1101", b="100";
cout << addBinary(a, b) << endl;
return 0;
}
class solution
{
public :
string addBinary(string a , string b)
{
string result ;
int i = a.size()-1, j = b.size()-1;
int carry = 0; // initially carry will be 0
while( i >= 0 || j >= 0)
{
int sum = carry;
if(i >= 0 ) sum = sum + a[i--] - '0'; // ascii value addition
if(j>= 0 ) sum = sum + a[j--] - '0';
carry = sum > 1 ? 1 : 0 // is sum is greather than 1 then carry wil generated otherwise no
result = result + to_string(sum%2)
}
if(carry) result += to_string(carry);
reverse(result.begin().result.end());
return result ;
}
};