Untitled

mail@pastecode.io avatar
unknown
c_cpp
a month ago
1.3 kB
3
Indexable
Never
char* addBinary(char* a, char* b)
{
    int a_len = (int)strlen(a);
    int b_len = (int)strlen(b);
    size_t big = (a_len > b_len) ? a_len : b_len;
    a_len--;
    b_len--;
  
    char *res = (char *)calloc(big + 2, sizeof(char));

    if (res == NULL)
    {
        return NULL;
    }

    int sum = 0;

    for (int i = big; i >= 0; --i)
    {
        if (a_len >= 0)
        {
            sum += a[a_len--] - '0';
        }
        if (b_len >= 0)
        {
            sum += b[b_len--] - '0';
        }

        switch (sum)
        {
            case 0:
            {
                res[i] = '0';
                break;
            }
            case 1:
            {
                res[i] = '1';
                sum = 0;
                break;
            }
            case 2:
            {
                res[i] = '0';
                sum = 1;
                break;
            }
            case 3:
            {
                res[i] = '1';
                sum = 1;
                break;
            }
            default:
                break;
        }
    }

    if (res[0] == '0')
    {
        for (int i = 0; i < big; ++i)
        {
            res[i] = res[i + 1];
        }
        res[big] = 0;
    }

    return res;
}
Leave a Comment