1.问题描述
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” 来自 https://leetcode.com/problems/add-binary/description/
2.题目分析
对两个二进制的字符串进行求和运算,需要注意字符和数字的转换,利用字符’0’的ascII码为48进行计算。以及结果是类似于尾插法,因此结果要进行字符串反转。
3.c++代码
string addBinary(string &a, string &b)
{
string r;
int m = a.length() -
1;
int n = b.length() -
1;
int c =
0;
while (m > -
1 || n > -
1)
{
int left = m > -
1 ? (
int)a[m]-
48 :
0;
int right = n > -
1 ? (
int)b[n]-
48 :
0;
int sum = left + right + c;
c =
sum /
2 ;
sum =
sum %
2;
r = r + (
char)(
sum+
48);
if( m>-
1) m--;
if (n >-
1) n--;
}
if (c ==
1)r = r +
'1';
for (
int i =
0, j = r.length() -
1; i<j; i++, j--)
{
char c = r[i];
r[i] = r[j];
r[j] = c;
}
return r;
}
string addBinary(
string a,
string b)
{
string result =
"";
int c =
0;
int i = a.
size() -
1;
int j = b.
size() -
1;
while (i >=
0 || j >=
0 || c ==
1)
{
c += i >=
0 ? a[i--] -
'0' :
0;
c += j >=
0 ? b[j--] -
'0' :
0;
result = char(c %
2 +
'0') + result;
c /=
2;
}
return result;
}
4.字符串反转
void reverse(
char *s,
int n)
{
for (
int i =
0, j = n -
1; i < j; i++, j--)
{
char c = s[i];
s[i] = s[j];
s[j] = c;
}
}