Trong bài này, chúng ta sẽ hiểu cách thêm hai chuỗi nhị phân trong Java. Chuỗi nhị phân là một chuỗi các số được biểu thị bằng byte 0 và 1.
Dưới đây là một minh chứng về điều tương tự -
Đầu vào
Giả sử đầu vào của chúng tôi là -
10101 10001
Đầu ra
Đầu ra mong muốn sẽ là -
100110
Thuật toán
Step 1- START Step 2- Create new scanner object Step 3- Enter two binary inputs Step 4- Define a carry flag Step 5- Use while condition to check if they are equal to 0 Step 6- If not, use the % operator and the carry flag to perform bitwise addition Step 7-Display it as result Step 8-STOP
Ví dụ 1
Ở đây, đầu vào đang được người dùng nhập dựa trên lời nhắc. Bạn có thể thử trực tiếp ví dụ này trong công cụ nền tảng mã hóa của chúng tôi
.
import java.util.*;
public class AddBinaryNumbers {
public static void main(String[] args) {
long binary_input_1 , binary_input_2 ;
System.out.println("Required packages have been imported");
Scanner input = new Scanner(System.in);
System.out.println("A reader object has been defined ");
System.out.print("Enter the first binary number : ");
binary_input_1 = input.nextLong();
System.out.print("Enter the second binary number : ");
binary_input_2 = input.nextLong();
int i, carry ;
i = 0;
carry = 0;
int[] binary_sum = new int[10];
while (binary_input_1 != 0 || binary_input_2 != 0) {
binary_sum[i++] = (int) (carry + (binary_input_1 % 10 + binary_input_2 % 10) % 2);
carry = (int) ((binary_input_1 % 10 + binary_input_2 % 10 + carry) / 2);
binary_input_1 = binary_input_1 / 10;
binary_input_2 = binary_input_2 / 10;
}
if (carry != 0) {
binary_sum[i++] = carry;
}
--i;
System.out.print("\nThe sum of the binary numbers is: ");
while (i >= 0) {
System.out.print(binary_sum[i--]);
}
System.out.print("\n");
}
} Đầu ra
Required packages have been imported A reader object has been defined The first binary number is 10101 The second binary number is 10001 The sum of the binary is: 100110
Ví dụ 2
Ở đây, số nguyên đã được xác định trước đó và giá trị của nó được truy cập và hiển thị trên bảng điều khiển.
public class AddingBinaryNumbers {
public static void main(String[] args) {
long binary_input_1 , binary_input_2 ;
binary_input_1 = 10101;
binary_input_2 = 10001;
System.out.print("The first binary number is " + binary_input_1);
System.out.print("\nThe second binary number is " + binary_input_2);
int i, carry ;
i = 0;
carry = 0;
int[] binary_sum = new int[10];
while (binary_input_1 != 0 || binary_input_2 != 0) {
binary_sum[i++] = (int) (carry + (binary_input_1 % 10 + binary_input_2 % 10) % 2);
carry = (int) ((binary_input_1 % 10 + binary_input_2 % 10 + carry) / 2);
binary_input_1 = binary_input_1 / 10;
binary_input_2 = binary_input_2 / 10;
}
if (carry != 0) {
binary_sum[i++] = carry;
}
--i;
System.out.print("\nThe sum of the binary numbers is: ");
while (i >= 0) {
System.out.print(binary_sum[i--]);
}
System.out.print("\n");
}
} Đầu ra
The first binary number is 10101 The second binary number is 10001 The sum of the binary numbers is: 100110