Java 程式新增兩個二進位制字串
在本文中,我們將瞭解如何在 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP