• Add Binary


    Given two binary strings, return their sum (also a binary string).

    For example,
    a = "11"
    b = "1"
    Return "100".

    很简单的题,代码写麻烦了。注意string加的顺序。

    class Solution {
    public:
        string addBinary(string a, string b) {
            int la = a.length()-1;
            int lb = b.length()-1;
            string re;
            int flag = 0;
            while(la >= 0 && lb >= 0)
            {
                if(a[la] == '1' && b[lb] == '1')
                {
                    if(flag == 1)
                    re = "1" + re;
                    else
                    re = "0" + re;
                    flag = 1;
                    la--;
                    lb--;
                    continue;
                }
                if(a[la] == '1' || b[lb] == '1')
                {
                    if(flag == 1)
                    {
                        re = "0" + re;
                        flag = 1;
      
                    }
                    else
                    {
                        re = "1" + re;
                        flag = 0;
                    }
                    la--;
                    lb--;
                    continue;
                }
                if(a[la] == '0' || b[lb] == '0')
                {
                    if(flag==0) re = "0"+re;
                    else re = "1" +re;
                    flag=0;
                    la--;
                    lb--;
                    continue;
                }
            }
            while(la >=0)
            {
                if(a[la] == '1' && flag == 1)
                {
                    re = "0" +re;
                }
                else if(a[la] == '0' && flag == 0)
                {
                    re = "0" +re;
                    flag = 0;
                }
                else {re ="1" +re;flag = 0;}
                la--;
            }
            while(lb >=0)
            {
                if(b[lb] == '1' && flag == 1)
                {
                    re = "0" +re;
                }
                else if(b[lb] == '0' && flag == 0)
                {
                    re = "0" +re;
                    flag = 0;
                }
                else {re ="1" +re;flag = 0;}
                lb--;
            }
            if(flag == 1) re = "1"+re;
            return re;
            
        }
    };
    

      

  • 相关阅读:
    node异步转同步(循环)
    三级省市区PCASClass.js插件
    微信公众号基础总结(待更新)
    ES6详解
    webpack配置
    高性能 CSS3 动画
    github上传口令
    纯css3 实现3D轮播图
    优美的js代码,拿去玩~
    关于列举属性用点还是用【】
  • 原文地址:https://www.cnblogs.com/pengyu2003/p/3575051.html
Copyright © 2020-2023  润新知