题目描述:给定两个二进制字符串,返回他们的和(用二进制表示)。
输入为非空字符串且只包含数字 1 和 0。
示例 1:
输入: a = “11”, b = “1”
输出: “100”
示例 2:
输入: a = “1010”, b = “1011”
输出: “10101”
本题实现的就是一个经典的二进制加法器
源代码:
package pid67;
public class Solution {
public static String addBinary(String a,String b){
int lengthA = a.length();
int lengthB = b.length();
int length = (lengthA > lengthB)?lengthA+1:lengthB+1;
/*
* 将数组长度设为两个字符串中长度较大者的长度+1,是给最高位进位做准备。
* 有进位就用,没进位就不用。
* 下面将两个二进制数进行对齐。
*/
int[] addend1 = new int[length];
int p = lengthA-1;
for(int i=length-1;i>=0;i--){
if(p>=0){//字符串转整型比较麻烦,用判断来解决
if(a.charAt(p)=='1'){
addend1[i] = 1;
}else if(a.charAt(p)=='0'){
addend1[i] = 0;
}
p--;
}else{
addend1[i] = 0;
p--;
}
}
int[] addend2 = new int[length];
int q = lengthB-1;
for(int i=length-1;i>=0;i--){
if(q>=0){//字符串转整型比较麻烦,用判断来解决
if(b.charAt(q)=='1'){
addend2[i] = 1;
}else if(b.charAt(q)=='0'){
addend2[i] = 0;
}
q--;
}else{
addend2[i] = 0;
q--;
}
}
int[] result = new int[length];
/*
* 两二进制数对齐相加
*/
int carry = 0;//记录低位向高位的进位
int curr;
for(int i=length-1;i>=0;i--){
curr = addend1[i] + addend2[i] + carry;
if(curr == 3){
carry = 1;
result[i] = 1;
}else if(curr == 2){
carry = 1;
result[i] = 0;
}else{
carry = 0;
result[i] = curr;
}
}
//将result数组转成字符串
String res = new String();
if(result[0] == 0){
for(int i=1;i<length;i++){
res = res.concat(Integer.toString(result[i]));
}
}else if(result[0] == 1){
for(int i=0;i<length;i++){
res = res.concat(Integer.toString(result[i]));
}
}
return res;
}
public static void main(String[] args) {
String s1 = "111";
String s2 = "1";
String result = addBinary(s1,s2);
System.out.println(result);
}
}
性能表现良好: