Skip to content

Commit

Permalink
Time: 6 ms (30.37%), Space: 6.3 MB (86.82%) - LeetHub
Browse files Browse the repository at this point in the history
  • Loading branch information
Dipendra-Raghav committed Feb 14, 2023
1 parent a787de1 commit 1148670
Showing 1 changed file with 55 additions and 0 deletions.
55 changes: 55 additions & 0 deletions 0067-add-binary/0067-add-binary.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
class Solution {
public:
string addBinary(string a, string b) {
if(a.length()<b.length()){
reverse(a.begin(),a.end());
while(a.length()!=b.length()){
a+='0';
}
reverse(a.begin(),a.end());
}
else if(b.length()<a.length()){
reverse(b.begin(),b.end());
while(a.length()!=b.length()){
b+='0';
}
reverse(b.begin(),b.end());
}
int carry=0;
string ans;
for(int i=a.length()-1;i>=0;i--){
if(a[i]=='1' && b[i]=='1'){
carry+=1;
if(carry==2){
ans+='1';
carry--;
}
else{
ans+='0';
}
}
else if(a[i]=='0' && b[i]=='0'){
if(carry>=1){
carry--;
ans+='1';
}
else{
ans+='0';
}
}
else{
if(carry>=1){
ans+='0';
}
else{
ans+='1';
}
}
}
if(carry>0){
ans+='1';
}
reverse(ans.begin(),ans.end());
return ans;
}
};

0 comments on commit 1148670

Please sign in to comment.