C++ full adder algorithm


  • 1
    S

    this algorithm works like a hardware -full adder

    s= (a xor b xor cin), cout = ab+bc+ac

    class Solution {
        public:
            string addBinary(string a, string b) {
                int ax = a.size();
                int bx = b.size();
                int len = max(ax, bx) + 1;
                string s = "";
                char cin[len]= {'0'};
                for(int i = 0; i < len; i++) {
                    int x,y;
                    int c = cin[i]-'0';
                    if(ax-1-i < 0) x = 0;
                    else x = (int)(a[ax-1-i]-'0');
                    if(bx-1-i < 0) y = 0;
                    else y = (int)(b[bx-1-i]-'0');
                    
                    s = (char)(x xor y xor c + '0') + s;
                    cin[i+1] = ((x&y)|(y&c)|(x&c) + '0'); 
                }
                if(s[0] == '0') s.erase(s.begin());
                return s;
            }
        };

  • 0
    Y

    it is really not necessary to have "cin" as an array. Actually, it might be better to have "s" as a preset array of length=len.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.