0
点赞
收藏
分享

微信扫一扫

LeetCode:67.二进制求和

骑在牛背上看书 2022-03-31 阅读 32

67.二进制求和


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

方法一:暴力破解

设置两个指针,分别从两个字符串的尾部往前遍历,每遍历一个字符时,将该字符转换成数字进行相加操作,并判断是否需要进位,并对相加结果对2进行取余,将结果作为字符拼接到最终的结果字符串中。

代码实现

string addBinary(string a, string b) {
    string sRes = "";
    int nIndexA = a.size() - 1;
    int nIndexB = b.size() - 1;
    int nCrayy = 0;
    while (nIndexA >= 0 && nIndexB >= 0) {
      int nAdd = nCrayy + a[nIndexA] + b[nIndexB] - '0' - '0';
      nCrayy = nAdd / 2;
      nAdd %= 2;
      char  cAdd = nAdd + '0';
      sRes = cAdd + sRes;

      nIndexA--;
      nIndexB--;
    }

    for (; nIndexA >= 0; nIndexA--) {
      int nAdd = nCrayy + a[nIndexA] - '0';
      nCrayy = nAdd / 2;
      nAdd %= 2;
      char  cAdd = nAdd + '0';
      sRes = cAdd + sRes;
    }
    for (; nIndexB >= 0; nIndexB--) {
      int nAdd = nCrayy + b[nIndexB] - '0';
      nCrayy = nAdd / 2;
      nAdd %= 2;
      char  cAdd = nAdd + '0';
      sRes = cAdd + sRes;
    }
    if (nCrayy) {
      char c = nCrayy + '0';
      sRes = c + sRes;
    }

    return sRes;
  }

时间复杂度: O ( max ⁡ ( m , n ) ) O(\max(m,n)) O(max(m,n))
空间复杂度: O ( 1 ) O(1) O(1)


哈哈哈哈哈,刷题只会暴力求解。

举报

相关推荐

0 条评论