题目:
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”
解析:二进制加法。当两个字符串长度不相同时,在短字符串前用0补齐;字符串和int类型数据之间的转换;字符类型数据转换为数字。
方法:
class Solution {
public:
string addBinary(string a, string b) {
int as=a.size()-1;
int bs=b.size()-1;
int carry=0;
string res="";
while(as>=0 || bs>=0)//短字符前补0
{
int q=as>=0?a[as--]-'0':0;//将字符转换为数字,ASCALL码相减。
int p=bs>=0?b[bs--]-'0':0;
int sum=q+p+carry;
res=to_string(sum%2)+res;//将int型数据转换为string类型
carry=sum/2;
}
if(carry == 1)
res="1"+res;//string类型数据相加
return res;
}
};