Binary Addition
binary addition code seed
import java.util.Scanner;
public class Binary
{
public static void main(String[] args)
{
System.out.println("Add two binary numbers");
Scanner scnr = new Scanner(System.in);
System.out.println("First number :");
String first = scnr.next();
System.out.println(first);
System.out.println("Second number :");
String second = scnr.next();
System.out.println(second);
String addition = add(first, second);
System.out.println(first + " + " + second + " = " + addition);
scnr.close();
}
}
public static String add(String first, String second) {
int b1 = Integer.parseInt(first, 2); // turns string into integer with base 2 (binary numbers)
int b2 = Integer.parseInt(second, 2);
int sum = b1 + b2;
return Integer.toBinaryString(sum); //returns as binary string
}
Binary.main(null);