我试图通过将数字放入char数组来对每个数字进行补全,并使用if条件对每个数字进行补全。应该覆盖每个结果,并且应该将每个结果保存在字符串result
中,但是整个操作的结果始终为空白。 Java调试器无法正常工作,我不明白为什么它无法正常工作。
import java.util.Scanner;
public class BinaryAdder {
public static String add(String binary1, String binary2) {
String result = "";
char[] safea = binary1.toCharArray();
char[] safeb = binary2.toCharArray();
int lb1 = binary1.length() - 1;
int lb2 = binary2.length() - 1;
char reminder = 0;
while (lb1 != 0 || lb2 != 0) {
if (safea[lb1] == 0 && safeb[lb2] == 0 && reminder == 0) {
result += "0";
lb1--;
lb2--;
} else if (safea[lb1] == 1 && safeb[lb2] == 0 && reminder == 0) {
result += "1";
lb1--;
lb2--;
} else if (safea[lb1] == 1 && safeb[lb2] == 1 && reminder == 0) {
result += "0";
reminder = 1;
lb1--;
lb2--;
} else if (safea[lb1] == 1 && safeb[lb2] == 1 && reminder == 1) {
result += "1";
reminder = 1;
lb1--;
lb2--;
} else if (safea[lb1] == 1 && safeb[lb2] == 0 && reminder == 1) {
result += "0";
reminder = 1;
lb1--;
lb2--;
} else if (safea[lb1] == 0 && safeb[lb2] == 1 && reminder == 1) {
result += "0";
reminder = 1;
lb1--;
lb2--;
} else if (safea[lb1] == 0 && safeb[lb2] == 1 && reminder == 0) {
result += "1";
lb1--;
lb2--;
} else if (safea[lb1] == 0 && safeb[lb2] == 0 && reminder == 1) {
result += "1";
lb1--;
lb2--;
}
}
return result;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Summand: ");
String input1 = scan.next("(0|1)*");
System.out.print("Summand: ");
String input2 = scan.next("(0|1)*");
scan.close();
System.out.println("Result: " + add(input1, input2));
}
}
答案 0 :(得分:1)
您可以使用Integer.parseInt(s, radix)
将这些位解析为整数。您需要使用2的基数:
public static String add(String binary1, String binary2) {
int i1 = Integer.parseInt(binary1, 2);
int i2 = Integer.parseInt(binary2, 2);
return Integer.toBinaryString(i1 + i2);
}