Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR CPP

binary string addition

//** fastest solution possible **//
#include <string_view>
#define int int_least8_t
class Solution {
public:
    string addBinary(const string_view& a, const string_view& b) {
        bool carry = 0;
        const string_view* small;
        const string_view* large;
        if(a.size() > b.size()) {
            small = &b;
            large = &a;
        }
        else {
            small = &a;
            large = &b;
        }
        
        string ans;
      	ans.reserve (a.size());
        int itrL = large[0].size() - 1;
        for(int i = small[0].size() - 1; i >= 0; i--) {
            if(small[0][i] == '1' && large[0][itrL] == '1' && carry == 1) {
                ans += "1";
                carry = 1;
            }
            else if(small[0][i] == '1' && large[0][itrL] == '1' && carry == 0) {
                ans += "0";
                carry = 1;
            }
            else if((small[0][i] == '1' && large[0][itrL] == '0' && carry == 0) 
                 || (small[0][i] == '0' && large[0][itrL] == '1' && carry == 0) ) {
                ans += "1";
                carry = 0;
            }
            else if(small[0][i] == '0' && large[0][itrL] == '0' && carry == 1){
                ans += "1";
                carry = 0;
            }
            else if(small[0][i] == '0' && large[0][itrL] == '0' && carry == 0){
                ans += "0";
                carry = 0;
            }
            else {
                ans += "0";
                carry = 1;
            }
            itrL--;
        }
        
        while(itrL >= 0){
             if(large[0][itrL] == '1' && carry == 1){
                ans+="0";
                carry=1;
            }
            else if((large[0][itrL] == '1' && carry == 0)
                 || (large[0][itrL] == '0' && carry == 1)){
                ans += "1";
                carry = 0;
            }
            else{
                ans += "0";
                carry = 0;
            }
            itrL--;
        }
        
        if(carry == 1){
            ans += "1";
        }
        
        reverse(ans.begin(), ans.end());
        return ans;
    }
};
#undef int
 
PREVIOUS NEXT
Tagged: #binary #string #addition
ADD COMMENT
Topic
Name
5+8 =