carloscn / structstudy

Leetcode daily trainning by using C/C++/RUST programming.
4 stars 1 forks source link

leetcode67:二进制求和(add-binary) #42

Open carloscn opened 2 years ago

carloscn commented 2 years ago

给你两个二进制字符串 a 和 b ,以二进制字符串的形式返回它们的和。

示例 1:

输入:a = "11", b = "1" 输出:"100" 示例 2:

输入:a = "1010", b = "1011" 输出:"10101"   提示:

1 <= a.length, b.length <= 104 a 和 b 仅由字符 '0' 或 '1' 组成 字符串如果不是 "0" ,就不含前导零

来源:力扣(LeetCode) 链接:https://leetcode.cn/problems/add-binary

carloscn commented 2 years ago

解题思路:

从字符串的尾巴开始便利,以最小的长度为遍历因子,记录carray、a、b字符串的位置,加和就好了。

#define C_OF(__c) ((int32_t)((__c) - '0'))
#define U_OF(__c) ((char)((__c) + '0'))

static int32_t add_binary(const char *str1,
                          const char *str2,
                          char **out_srt)
{
    int32_t ret = 0;
    int32_t str1_len = 0;
    int32_t str2_len = 0;
    int32_t max_len = 0;
    int32_t i = 0;
    int32_t a = 0, b = 0, c = 0, d = 0;

    UTILS_CHECK_PTR(str1);
    UTILS_CHECK_PTR(str2);
    UTILS_CHECK_PTR(out_srt);

    str1_len = strlen(str1);
    str2_len = strlen(str2);
    max_len = (str1_len > str2_len) ? str1_len : str2_len;

    *out_srt = (char*)calloc(1, max_len + 2);
    UTILS_CHECK_PTR(*out_srt);

    while (max_len --) {
        a = (i < str1_len) ? C_OF(*(str1 + str1_len - i - 1)) : 0;
        b = (i < str2_len) ? C_OF(*(str2 + str2_len - i - 1)) : 0;
        d = (a + b + c) & 1;            // equal to x % 2
        c = (a + b + c) >> 1;           // equal to x / 2
        *(*out_srt + max_len) = U_OF(d);
        i ++;
    }

    if (c) {
        memmove(*out_srt + 1, *out_srt, i + 1);
        **out_srt = U_OF(c);
    }

finish:
    return ret;
}
carloscn commented 2 years ago

code:

https://github.com/carloscn/structstudy/blob/master/c_programming/str/07_add-binary_67.c

result:

image