Java 程序:两个二进制数相加

编写一个Java程序,用一个例子来相加两个二进制数。众所周知,二进制数是1和0的组合。因此,相加两个就是 

  • 0 + 0 = 0
  • 0 + 1 = 1
  • 1 + 0 = 1
  • 1 + 1 = 10。这里,1会进位。
  • 1(进位) + 1 + 1 = 11,1会进位。
import java.util.Scanner;

public class Example {

	private static Scanner sc;
	
	public static void main(String[] args) {

		sc = new Scanner(System.in);
		
		System.out.println("Enter First and Second Numbers = ");	
		long b1 = sc.nextLong();
		long b2 = sc.nextLong();
		
		int i = 0, carry = 0;
		
		int[] sum = new int[10];
		
		while(b1 != 0 || b2 != 0)
		{
			sum[i++] = (int)((b1 % 10 + b2 % 10 + carry) % 2);
			carry    = (int)((b1 % 10 + b2 % 10 + carry) / 2);
			b1 /= 10;
			b2 /= 10;
		}
		if(carry != 0)
		{
			sum[i++] = carry;
		}
		--i;
		System.out.print("\nThe Total of the above Two = ");
		while(i >= 0)
		{
			System.out.print(sum[i--]);
		}
		System.out.println();
	}

}
Java Program to Add Two Binary Numbers

这个Java程序将二进制转换为整数,然后相加两个数。如果两个数都是字符串数据类型,我们可以使用Integer.parseInt方法将它们转换为整数,然后将这两个整数值相加。接下来,我们可以使用toBinaryString方法将它们转换回二进制数。

import java.util.Scanner;

public class Example2 {

	private static Scanner sc;
	
	public static void main(String[] args) {

		sc = new Scanner(System.in);
		
		System.out.println("Enter The First and Second Numbers = ");	
		String b1 = sc.nextLine();
		String b2 = sc.nextLine();
		
		int num1 = Integer.parseInt(b1, 2);
		int num2 = Integer.parseInt(b2, 2);
		
		int output = num1 + num2;
		
		System.out.print("\nThe Sum = ");
		System.out.print(Integer.toBinaryString(output));
	}
}
Enter The First and Second Numbers = 
101010
111111

The Sum = 1101001

此程序有助于使用for循环相加两个二进制数。请参考Java程序。

import java.util.Scanner;

public class Example3 {

	private static Scanner sc;
	
	public static void main(String[] args) {

		sc = new Scanner(System.in);
		
		System.out.println("Enter The First and Second Numbers = ");	
		long b1 = sc.nextLong();
		long b2 = sc.nextLong();
		
		int i, carry = 0;
		
		int[] sum = new int[10];
		
		for(i = 0; b1 != 0 || b2 != 0; b1 /= 10, b2 /= 10)
		{
			sum[i++] = (int)((b1 % 10 + b2 % 10 + carry) % 2);
			carry    = (int)((b1 % 10 + b2 % 10 + carry) / 2);		
		}
		if(carry != 0)
		{
			sum[i++] = carry;
		}
		--i;
		System.out.print("\nThe Sum = ");
		while(i >= 0)
		{
			System.out.print(sum[i--]);
		}
		System.out.println();
	}

}
Enter The First and Second Numbers = 
110101
010111

The Sum = 1001100