이 기사에서는 Java에서 두 개의 바이너리 문자열을 추가하는 방법을 이해할 것입니다. 이진 문자열은 바이트 0과 1로 표현되는 일련의 숫자입니다.
아래는 동일한 데모입니다 -
입력
입력이 -
라고 가정합니다.10101 10001
출력
원하는 출력은 -
100110
알고리즘
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
예시 1
여기에서 입력은 프롬프트에 따라 사용자가 입력하고 있습니다. 우리코딩 그라운드 도구에서 이 예제를 라이브로 사용해 볼 수 있습니다.
.
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");
}
} 출력
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
예시 2
여기서 정수는 이전에 정의되었으며 그 값은 콘솔에 액세스되어 표시됩니다.
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");
}
} 출력
The first binary number is 10101 The second binary number is 10001 The sum of the binary numbers is: 100110