zoukankan      html  css  js  c++  java
  • 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;
            
        }
    };
    

      

  • 相关阅读:
    [YTU]_2536( C++ 长方体继承自矩形)
    [YTU]_2560(C++继承(改错题))
    [YTU]_2532(投简历)
    [YTU]_2621(B 继承 圆到圆柱体)
    stl
    noip2008双栈排序
    倍增入门水题
    noip模拟【ping】
    dp入门(LIS,LCS)
    【Luogu 1799】数列
  • 原文地址:https://www.cnblogs.com/pengyu2003/p/3575051.html
Copyright © 2011-2022 走看看