请写Java代码。【题目描述】:输入两个二进制数,求两个数相加的结果【输入格式】:从键盘输入两个正整数n1和n2,代表两个二进制数的位数,接下来两行输入长度分别为n1和n2的数组,数组元素为0或者1(长度大于1时,第一个元素必不为0),数组元素用空格隔开【输出格式】:依次输出一个由0和1组成的数组,表示输入的两个二进制数的和
时间: 2023-04-06 07:04:30 浏览: 132
以下是Java代码:
import java.util.Scanner;
public class BinaryAddition {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n1 = input.nextInt();
int n2 = input.nextInt();
int[] a = new int[n1];
int[] b = new int[n2];
for (int i = 0; i < n1; i++) {
a[i] = input.nextInt();
}
for (int i = 0; i < n2; i++) {
b[i] = input.nextInt();
}
int[] sum = addBinary(a, b);
for (int i = 0; i < sum.length; i++) {
System.out.print(sum[i] + " ");
}
}
public static int[] addBinary(int[] a, int[] b) {
int n = Math.max(a.length, b.length);
int[] sum = new int[n];
int carry = 0;
for (int i = 0; i < n; i++) {
int ai = i < a.length ? a[a.length - 1 - i] : 0;
int bi = i < b.length ? b[b.length - 1 - i] : 0;
sum[n - 1 - i] = (ai + bi + carry) % 2;
carry = (ai + bi + carry) / 2;
}
if (carry > 0) {
int[] newSum = new int[n + 1];
newSum[0] = carry;
for (int i = 0; i < n; i++) {
newSum[i + 1] = sum[i];
}
return newSum;
}
return sum;
}
}
阅读全文