LeetCode //C - 67. Add Binary

67. Add Binary

Given two binary strings a and b , return their sum as a binary string.

Example 1:

Input: a = "11", b = "1"
Output: "100"

Example 2:

Input: a = "1010", b = "1011"
Output: "10101"

Constraints:
  • 1 < = a . l e n g t h , b . l e n g t h < = 1 0 4 1 <= a.length, b.length <= 10^4 1<=a.length,b.length<=104
  • a and b consist only of '0' or '1' characters.
  • Each string does not contain leading zeros except for the zero itself.

From: LeetCode

Link: 67. Add Binary


Solution:

Ideas:
  1. Determine the Lengths: The lengths of the input strings a and b are determined using strlen.

  2. Allocate Memory: Memory is dynamically allocated for the result string, which must be long enough to hold the sum of the two binary strings plus a possible carry bit at the beginning and a null terminator at the end.

  3. Initialize Result: The allocated result string is initialized with '0's to prepare for the addition operation. This also handles edge cases where the input strings are "0".

  4. Perform Binary Addition:

  • Starting from the rightmost bit (least significant bit) of both strings, each bit is added along with any carry from the previous addition.
  • The sum of the two bits and the carry is computed. The resulting bit (either '0' or '1') is stored in the corresponding position in the result string, and the carry (either 0 or 1) is updated for the next iteration.
  • The loop continues, moving left through the strings until all bits have been processed.
  1. Handle Final Carry: After the loop, if there is a remaining carry, it is placed at the beginning of the result string.

  2. Adjust Result:

  • If there is no carry and the result starts with '0', this leading '0' is unnecessary (except in the case where the result is actually "0"), so it is removed. This is done by creating a copy of the string starting from result[1] and freeing the original result.
  • If there is a carry or the result does not start with '0', the result is returned as is.
Code:
c 复制代码
char* addBinary(char* a, char* b) {
    int lengthA = strlen(a);
    int lengthB = strlen(b);
    int maxLen = lengthA > lengthB ? lengthA : lengthB;
    char* result = (char*)malloc(maxLen + 2); // +1 for possible carry, +1 for '\0'
    
    if (result == NULL) {
        return NULL; // Handle allocation failure if needed
    }
    
    // Initialize the result with '0's to handle the case where a and b are "0"
    for (int i = 0; i < maxLen + 2; i++) {
        result[i] = '0';
    }
    
    int carry = 0; // Initialize the carry
    result[maxLen + 1] = '\0'; // Null-terminate the result
    int i = lengthA - 1;
    int j = lengthB - 1;
    int k = maxLen; // Start from the end of the result

    // Add each bit from right to left
    while (i >= 0 || j >= 0 || carry) {
        int sum = carry;
        if (i >= 0) {
            sum += a[i] - '0'; // Convert from char to int and add to sum
            i--;
        }
        if (j >= 0) {
            sum += b[j] - '0'; // Convert from char to int and add to sum
            j--;
        }
        carry = sum / 2; // Update carry
        result[k] = (sum % 2) + '0'; // Determine the bit to store as char
        k--;
    }

    // Check if there is a carry that used the extra space at the beginning
    if (carry) {
        result[0] = '1';
        return result;
    } else {
        // If the first character is '0' and there was no carry, we need to skip it
        if (result[0] == '0') {
            char* shifted_result = strdup(result + 1);
            free(result);
            return shifted_result;
        } else {
            // If the first character is not '0', we just return the result as is
            return result;
        }
    }
}
相关推荐
cici1587416 分钟前
二值化断裂裂缝的智能拼接算法
人工智能·算法·计算机视觉
麦格芬23023 分钟前
LeetCode 763 划分字母区间
算法·leetcode·职场和发展
福尔摩斯张40 分钟前
C++核心特性精讲:从C语言痛点出发,掌握现代C++编程精髓(超详细)
java·linux·c语言·数据结构·c++·驱动开发·算法
涛涛北京1 小时前
【强化学习实验】- 策略梯度算法
人工智能·算法
栀秋6661 小时前
深入浅出链表操作:从Dummy节点到快慢指针的实战精要
前端·javascript·算法
Pyeako2 小时前
机器学习之KNN算法
人工智能·算法·机器学习
xhxxx2 小时前
从被追问到被点赞:我靠“哨兵+快慢指针”展示了面试官真正想看的代码思维
javascript·算法·面试
可信计算2 小时前
【算法随想】一种基于“视觉表征图”拓扑变化的NLP序列预测新范式
人工智能·笔记·python·算法·自然语言处理
月明长歌2 小时前
【码道初阶】【LeetCode 110】平衡二叉树:如何用一个“Magic Number”将复杂度从O(N²)降为 O(N)?
linux·算法·leetcode
yaoh.wang2 小时前
力扣(LeetCode) 14: 最长公共前缀 - 解法思路
python·程序人生·算法·leetcode·面试·职场和发展·跳槽