一、题目叙述:
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
Subscribe to see which companies asked this question.
二、解题思路:
Easy题,我很佩服我的解法,真的好。。。烂,一个简单题写成这样。。。
(1)先把两个字符串长度填成一样转换成字符数组
(2)将字符数组内容倒序相加放进结果字符串(我麻烦的分情况写了。。。)
三、源码:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Solution
{
public String addBinary(String a, String b)
{
String tmp = "";
if (a.length() >= b.length())
{
for (int i = 0; i < a.length() - b.length(); i++)
tmp += "0";
b = tmp + b;
}
else
{
for (int i = 0; i < b.length() - a.length(); i++)
tmp += "0";
a = tmp + a;
}
char[] aa = a.toCharArray();
char[] bb = b.toCharArray();
String res = "";
int len = aa.length - 1;
// int bl = bb.length - 1;
int n = 0;
while (len >= 0)
{
if (aa[len] == '1' && bb[len] == '1' )
{ res = n + res; n = 1;}
else if (aa[len] == '0' && bb[len] == '0')
{ res = n + res; n = 0;}
else if (n == 1)
{ res = "0" + res; n = 1;}
else
{ res = "1" + res; n = 0;}
len--;
}
if (n == 1) res = "1" + res;
return res;
}
public static void main(String args[])
{
String a = "";
String b = "";
// int[] digits = {0};
Solution solution = new Solution();
// int[][] abc = {{2,5},{8,4}};
// int[] b = {2,3,4};
// for(int i = 0; i < abc.length; i ++)
System.out.print(solution.addBinary(a, b));
}
}