Code18 二进制求和

题目

leetcode67. 二进制求和
给你两个二进制字符串,返回它们的和(用二进制表示)。
输入为 非空 字符串且只包含数字 1 和 0。

示例 1:
输入: a = “11”, b = “1”
输出: “100”

示例 2:
输入: a = “1010”, b = “1011”
输出: “10101”

提示:
每个字符串仅由字符 ‘0’ 或 ‘1’ 组成。
1 <= a.length, b.length <= 10^4
字符串如果不是 “0” ,就都不含前导零。

代码
  • Code17 加一 大致思路一致,在考虑进位时稍复杂些,需要从字符转为数字,且进制是二进制而不是十进制。
  • C代码
  • 思路:
    • C代码涉及 malloc , 所以需要先确认申请资源的大小,但一开始并不能确定是否有最后的进位,所以先申请字符串a,b中较长长度大小等同的资源,
      • 最后若有进位,重新申请一块资源,将结果拷贝过去,并释放第一块资源。
      • 最后若无进位,直接返回结果。
#include <string.h>
#include <malloc.h>
char* addBinary(char* a, char* b) {
  int a_len = strlen(a);
  int b_len = strlen(b);
  int len = a_len > b_len ? a_len : b_len;
  // 申请第一块资源
  char* s = (char*)malloc(sizeof(char) * (len + 1));
  s[len] = '\0';

  int carry = 0; // 进位
  int a_idx = a_len - 1; // 最后一个字符下标向前遍历
  int b_idx = b_len - 1; // 最后一个字符下标向前遍历
  int s_idx = len - 1;   // 用于结果填充下标
  while(a_idx >= 0 || b_idx >= 0){
    int aidx_num = a_idx < 0 ? 0 : a[a_idx] - '0';
    int bidx_num = b_idx < 0 ? 0 : b[b_idx] - '0';
    s[s_idx--] = (aidx_num + bidx_num + carry) % 2 + '0'; // 加法逻辑:本位用模
    carry = (aidx_num + bidx_num + carry) / 2; // 加法逻辑:进位用除

    --a_idx;
    --b_idx;
  }

  if (carry) { // 有最后进位
    // 重新申请资源,比第一块资源长度 + 1, 用于放最后进位
    char* res = (char*)malloc(sizeof(char) * (len + 1 + 1)); 
    res[0] = carry + '0'; // 第1位放最后进位
    memcpy(res + 1, s, len + 1); // 拷贝剩余结果
    free(s); // 释放第一块资源
    return res;
  }else{
    return s; // 无最后进位,直接返回
  }
}
  • C++代码
    • 不涉及资源申请问题,在string中采用前插即可。
#include <string>
using namespace std;

class Solution {
 public:
  string addBinary(string a, string b) {
    string res;
    int carry = 0;
   
    auto a_it = a.rbegin();
    auto b_it = b.rbegin();
    while(a_it < a.rend() || b_it < b.rend()){
      int a_num = a_it >= a.rend() ? 0 : *a_it - '0';
      int b_num = b_it >= b.rend() ? 0 : *b_it - '0';
      res.insert(res.begin(), (a_num + b_num + carry) % 2 + '0');
      carry = (a_num + b_num + carry) / 2;

      ++a_it;
      ++b_it;
    }
    if (carry){
      res.insert(res.begin(), carry + '0');
    }

    return res;
  }
};
测试
#include <iostream>
int main() {
  {
    char* a = "1010";
    char* b = "1011";
    char* s = addBinary(a, b);
    cout << s << endl;
    free(s);
  }
  {
    string a = "1010";
    string b = "1011";
    Solution s;
    cout << s.addBinary(a, b);
  }
  cin.get();
  return 0;
}
  • 结果
10101
10101
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值