鱼C论坛

 找回密码
 立即注册
查看: 1750|回复: 0

[技术交流] C++刷leetcode(67. 二进制求和)【递归】

[复制链接]
发表于 2020-6-6 20:37:38 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
题目描述:
  1. 给你两个二进制字符串,返回它们的和(用二进制表示)。

  2. 输入为 非空 字符串且只包含数字 1 和 0。

  3.  

  4. 示例 1:

  5. 输入: a = "11", b = "1"
  6. 输出: "100"
  7. 示例 2:

  8. 输入: a = "1010", b = "1011"
  9. 输出: "10101"
  10.  

  11. 提示:

  12. 每个字符串仅由字符 '0' 或 '1' 组成。
  13. 1 <= a.length, b.length <= 10^4
  14. 字符串如果不是 "0" ,就都不含前导零。

  15. 来源:力扣(LeetCode)
  16. 链接:https://leetcode-cn.com/problems/add-binary
  17. 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
复制代码


  1. class Solution {
  2. public:
  3.     void dfs(string & a, string & b, string& res, int cura, int curb, int store){
  4.         if(cura < 0 && curb < 0){
  5.             if(store != 0) res += '1';
  6.             return;
  7.         }
  8.         if(cura < 0){
  9.             int temp = b[curb] - '0' + store;
  10.             if(temp >= 2){
  11.                 store = 1;
  12.                 if(temp == 2)res += '0';
  13.                 else res += '1';
  14.             }
  15.             else if(temp < 2){
  16.                 char temp2 = temp + '0';
  17.                 res += temp2;
  18.                 store = 0;
  19.             }
  20.             dfs(a, b, res, -1, curb - 1, store);
  21.         }
  22.         else if(curb < 0){
  23.             int temp = a[cura] - '0' + store;
  24.             if(temp >= 2){
  25.                 store = 1;
  26.                 if(temp == 2)res += '0';
  27.                 else res += '1';
  28.             }
  29.             else if(temp < 2){
  30.                 char temp2 = temp + '0';
  31.                 res += temp2;
  32.                 store = 0;
  33.             }

  34.             dfs(a, b, res, cura-1, -1, store);
  35.         }
  36.         else{
  37.             int temp = a[cura] - '0' + b[curb] - '0' + store;
  38.             if (temp >= 2){
  39.                 store = 1;
  40.                 if(temp == 2)res += '0';
  41.                 else res += '1';
  42.             }else if(temp < 2){
  43.                 char temp2 = temp + '0';
  44.                 res += temp2;
  45.                 store = 0;
  46.             }
  47.             dfs(a, b, res, cura-1, curb-1, store);
  48.         }
  49.     }
  50.     string addBinary(string a, string b) {
  51.         string res;
  52.         dfs(a, b, res, a.size()-1, b.size() - 1, 0);
  53.         reverse(res.begin(), res.end());
  54.         return res;
  55.     }
  56. };
复制代码

本帖被以下淘专辑推荐:

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-7-8 02:07

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表