-
Notifications
You must be signed in to change notification settings - Fork 0
/
Add Binary.cpp
64 lines (44 loc) · 1.29 KB
/
Add Binary.cpp
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
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.
code*******
#include <bits/stdc++.h>
using namespace std;
void addBinary(string a, string b) {
int i = a.size()-1;
int j = b.size()-1;
int carry = 0;
string ans = "";
while(i>=0 || j>=0)
{
if(i>=0)
{
carry += a[i] - '0'; // store last number in carry
i--; // decrement 1st string of index
}
// same as 2nd string
if(j>=0)
{
carry += b[j] - '0'; // store last number in carry
j--; //decrement 2nd string of index
}
ans += (carry%2) + '0';
carry = carry/2;
}
if(carry)ans += '1'; // if value of carry is still there
reverse(ans.begin() , ans.end());
cout<<ans;
}
int main()
{
addBinary("11","1");
return 0;
}