两个binary string相加输出binary string, 给出基本解法后,更改输入是一个string集合,输出不变,然后问如何降低空间复杂度
addKBinary 要求是一个新的函数,不需要调用addbinary,其实就是把第四行的while loop改成适用 list of string
public static void main(String[] args) {
String a = "10011";
String b = "11010";
String c = "1011";
String d = "100";
String e = "101111";
String[] list = { a, b, c, d, e };
System.out.println(addBinary(a, b));
System.out.println(addKBinary1(list));
System.out.println(addKBinary2(list));
}
public static String addBinary(String a, String b) {
StringBuilder sb = new StringBuilder();
int i = a.length() - 1, j = b.length() - 1, carry = 0;
while (i >= 0 || j >= 0) {
int sum = carry;
if (j >= 0)
sum += b.charAt(j--) - '0';
if (i >= 0)
sum += a.charAt(i--) - '0';
sb.append(sum % 2);
carry = sum / 2;
}
if (carry != 0)
sb.append(carry);
return sb.reverse().toString();
}
public static String addKBinary1(String[] list) {
String sum = list[0];
for (int i = 1; i < list.length; i++) {
sum = addBinary(sum, list[i]);
}
return sum;
}
public static String addKBinary2(String[] list) {
StringBuilder sb = new StringBuilder();
String sum = list[0];
for (int k = 1; k < list.length; k++) {
int i = sum.length() - 1, j = list[k].length() - 1, carry = 0;
while (i >= 0 || j >= 0) {
int temp = carry;
if (j >= 0)
temp += list[k].charAt(j--) - '0';
if (i >= 0)
temp += sum.charAt(i--) - '0';
sb.append(temp % 2);
carry = temp / 2;
}
if (carry != 0)
sb.append(carry);
sum = sb.reverse().toString();
sb = new StringBuilder();
}
return sum;
}