Java 程序添加两个二进制字符串

javaobject oriented programmingprogramming更新于 2024/4/12 3:24:17

在本文中,我们将了解如何在 Java 中添加两个二进制字符串。二进制字符串是用字节 0 和 1 表示的数字序列。

下面是相同的演示 −

输入

假设我们的输入是 −

10101
10001

输出

所需的输出将是 −

100110

算法

步骤 1- 开始
步骤 2- 创建新的扫描仪对象
步骤 3- 输入两个二进制输入
步骤 4- 定义进位标志
步骤 5- 使用 while 条件检查它们是否等于 0
步骤 6- 如果不相等,使用 % 运算符和进位标志执行按位加法
步骤 7- 将其显示为结果步骤 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

相关文章


有用资源