• Leetcode 067. 二进制求和 大数加法


    地址 https://leetcode-cn.com/problems/add-binary/

    给你两个二进制字符串,返回它们的和(用二进制表示)。
    
    输入为 非空 字符串且只包含数字 1 和 0。
    
     
    
    示例 1:
    
    输入: a = "11", b = "1"
    输出: "100"
    示例 2:
    
    输入: a = "1010", b = "1011"
    输出: "10101"
     
    
    提示:
    
    每个字符串仅由字符 '0''1' 组成。
    1 <= a.length, b.length <= 10^4
    字符串如果不是 "0" ,就都不含前导零。

    解答

    字符串的大数加法 不过是二进制

    class Solution {
    public:
       
        
        string addBinary(string a, string b) {
        char next = '0';
        string ans;
        reverse(a.begin(), a.end());
        reverse(b.begin(), b.end());
    
        int al = 0; int bl = 0;
        while (al < a.size() && bl < b.size()) {
            int total = (a[al] - '0') + (b[bl] - '0') + (next - '0');
    
            if (total == 3) {
                ans += "1"; next = '1';
            }
            else if (total == 2) {
                ans += "0"; next = '1';
            }
            else if (total == 1) {
                ans += "1"; next = '0';
            }
            else if (total == 0) {
                ans += "0"; next = '0';
            }
    
            al++; bl++;
        }
    
        while (al < a.size()) {
            if (a[al] == '1' && next == '1') {
                ans += "0"; next = '1';
            }
            else if (a[al] == '0' && next == '0') {
                ans += "0"; next = '0';
            }
            else {
                ans += "1"; next = '0';
            }
            al++;
        }
    
        while (bl < b.size()) {
            if (b[bl] == '1' && next == '1') {
                ans += "0"; next = '1';
            }
            else if (b[bl] == '0' && next == '0') {
                ans += "0"; next = '0';
            }
            else {
                ans += "1"; next = '0';
            }
            bl++;
        }
    
        if (next == '1') {
            ans += next;
        }
        reverse(ans.begin(), ans.end());
        return ans;
    }
    
        
    };
    作 者: itdef
    欢迎转帖 请保持文本完整并注明出处
    技术博客 http://www.cnblogs.com/itdef/
    B站算法视频题解
    https://space.bilibili.com/18508846
    qq 151435887
    gitee https://gitee.com/def/
    欢迎c c++ 算法爱好者 windows驱动爱好者 服务器程序员沟通交流
    如果觉得不错,欢迎点赞,你的鼓励就是我的动力
    阿里打赏 微信打赏
  • 相关阅读:
    关于webpack升级过后不能打包的问题;
    数组的一些理解
    .NET(C#):使用Win32Exception类型处理Win32错误代码
    托管代码和非托管代码
    托管DLL和非托管DLL的区别
    C#实现Dll(OCX)控件自动注册的两种方法(转)
    Com组件和Dll文件区别
    C#创建COM组件
    ajaxFileUpload插件上传文件 返回 syntaxError :unexpected token
    jquery插件--ajaxfileupload.js上传文件原理分析
  • 原文地址:https://www.cnblogs.com/itdef/p/13183321.html
Copyright © 2020-2023  润新知