67. Add Binary(字符串加减,三目运算符)


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

The input strings are both non-empty and contains only characters 1 or 0.

Example 1:

Input: a = "11", b = "1"
Output: "100"

Example 2:

Input: a = "1010", b = "1011"
Output: "10101"

 法1:首先比较两个字符创的大小,比较小的字符串在前面补上字符0;然后再取较大的那个字符串长度操作循环,从尾部开始,将两个字符串与‘0’字符的差相加(结合进1标志carry考虑是否+1),结果temp分别讨论。以较大的字符串长度创一个新字符串,将temp插入,同时返回是否进1标志carry 。

 
  

class Solution {
public:
string addBinary(string a, string b) {

int na =a.size()-1;
int nb =b.size()-1;
if (na >nb) for (int i=0;i<na-nb;i++) b.insert(b.begin (),'0');
else if (na<nb) for (int i=0;i<nb-na;i++) a.insert (a.begin (),'0');

int n=max(na,nb);
bool carry =false ;
string res;

for (int i=n;i>=0;i--)
{
int temp=0;
if (carry) temp=(a[i]-'0')+(b[i]-'0')+1;//字符之间相减返回int;
else temp=(a[i]-'0')+(b[i]-'0');
if (temp==0)
{
res.insert(res.begin(),'0');//string的insert()函数;
carry =false ;
}
if (temp==1)
{
res.insert(res.begin(),'1');
carry=false ;
}
if(temp==2)
{
res.insert(res.begin(),'0');
carry=true;
}
if(temp==3)
{
res.insert(res.begin(),'1');
carry=true;
}
}
if(carry) res.insert(res.begin(),'1');
return res;
}
};

 

法2:通过从两个字符串末尾逐个计算来完成,保留两数相加%2,而将两数相加/2作为进1标志。如果刷到前面较小字符串没有字符了就设置为0继续操作直到都小于0;

class Solution {
public:
    string addBinary(string a, string b) {
        int na =a.size()-1;
        int nb=b.size()-1;
        string res="";
        int carry =0;
        
        while (na>=0||nb>=0)
        {
            
            int p= na>=0? a[na--]-'0':0;//三目运算符的简便性;
            int q= nb>=0? b[nb--]-'0':0;
            int sum=p+q+carry;
            res =to_string (sum%2)+res;
            carry=sum/2;
        }
        return carry==1? '1'+res:res;
}
};

猜你喜欢

转载自www.cnblogs.com/xiaofeixiawar/p/9102353.html