Accepted 0ms C Solution


  • 1
    M
    char* addBinary(char* a, char* b) {
        int n, m;
        for (n=0; *a; a++, n++) ;
        for (m=0; *b; b++, m++) ;
        char *p = (char*)malloc(m>n ? m+2 : n+2), *last = p;
        int c = 0;
        while (n || m || c) {
            int s = c;
            if (n) {
                s += *(--a)-'0';
                --n;
            }
            if (m) {
                s += *(--b)-'0';
                --m;
            }
            *last++ = (s&1)+'0';
            c = s>>1;
        }
        *last=0;
        char *start = p, t;
        while (start+1 < last) { // reverse string
            t = *start;
            *start++=*(--last);
            *last=t;
        }
        return p;
    }

Log in to reply
 

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