19

Does anyone know how to add 2 binary numbers, entered as binary, in Java?

For example, 1010 + 10 = 1100.

Ephemera
  • 8,672
  • 8
  • 44
  • 84
PulsePanda
  • 1,806
  • 10
  • 33
  • 56
  • @twiddles No more homework tagging! :) – squiguy Mar 07 '13 at 06:45
  • This may blow your mind. You can write C code in java. C is lower-level and you can do binary arithmetic with it. It's late, so I'm not writing out a sample, but you can look it up. – user817129 Oct 13 '13 at 10:01
  • This is more likely to be a leetcode question I guess. I came accross this question here: https://leetcode.com/problems/add-binary/ – Prometheus Oct 21 '22 at 08:48

22 Answers22

52

Use Integer.parseInt(String, int radix).

 public static String addBinary(){
 // The two input Strings, containing the binary representation of the two values:
    String input0 = "1010";
    String input1 = "10";

    // Use as radix 2 because it's binary    
    int number0 = Integer.parseInt(input0, 2);
    int number1 = Integer.parseInt(input1, 2);

    int sum = number0 + number1;
    return Integer.toBinaryString(sum); //returns the answer as a binary value;
}
inspired_learner
  • 142
  • 1
  • 11
Martijn Courteaux
  • 67,591
  • 47
  • 198
  • 287
  • wow. it worked! thanks bro. but i was wondering if you could explain why? – PulsePanda Dec 17 '11 at 23:13
  • `Integer` is a class, which contains a method to parse a string which represents an integer to its real integer value (`int`). You can take a look at the link I provided you. – Martijn Courteaux Dec 17 '11 at 23:14
  • Martin - it does not show the answer in binary. How do we do that? – Abhishek kumar Feb 16 '16 at 04:39
  • @Abhishekkumar just use `Integer.toBinaryString(sum);` – austin665 Mar 19 '16 at 18:31
  • 11
    This can throw java.lang.NumberFormatException: For input string: "10100000100100110110010000010101111011011001101110111111111101000000101111001110001111100001101" "110101001011101110001111100110001010100001101011101010000011011011001011101111001100000011011110011" – Tasneem Dec 08 '16 at 07:29
  • 3
    @Tasneem which makes sense since the max int value is `2,147,483,647` and the (first) binary value translates to `24,847,893,154,024,981,730,169,397,005` – Ivar Reukers May 17 '17 at 19:43
30

To dive into fundamentals:

public static String binaryAddition(String s1, String s2) {
    if (s1 == null || s2 == null) return "";
    int first = s1.length() - 1;
    int second = s2.length() - 1;
    StringBuilder sb = new StringBuilder();
    int carry = 0;
    while (first >= 0 || second >= 0) {
        int sum = carry;
        if (first >= 0) {
            sum += s1.charAt(first) - '0';
            first--;
        }
        if (second >= 0) {
            sum += s2.charAt(second) - '0';
            second--;
        }
        carry = sum >> 1;
        sum = sum & 1;
        sb.append(sum == 0 ? '0' : '1');
    }
    if (carry > 0)
        sb.append('1');

    sb.reverse();
    return String.valueOf(sb);
}
sbaker
  • 408
  • 5
  • 13
13

Martijn is absolutely correct, to piggyback and complete the answer

Integer.toBinaryString(sum);

would give your output in binary as per the OP question.

non sequitor
  • 18,296
  • 9
  • 45
  • 64
9

You can just put 0b in front of the binary number to specify that it is binary.

For this example, you can simply do:

Integer.toString(0b1010 + 0b10, 2);

This will add the two in binary, and Integer.toString() with 2 as the second parameter converts it back to binary.

haley
  • 1,165
  • 7
  • 13
  • Binary literals are allowed in java 7 too, see https://docs.oracle.com/javase/specs/jls/se7/html/jls-3.html#jls-3.10.1 – fabian Jun 07 '15 at 14:19
  • This should be the correct answer; no reason to convert to strings or roll your own solution. – Jason Jul 14 '16 at 18:16
5

The original solution by Martijn will not work for large binary numbers. The below code can be used to overcome that.

public String addBinary(String s1, String s2) {
    StringBuilder sb = new StringBuilder();
    int i = s1.length() - 1, j = s2.length() -1, carry = 0;
    while (i >= 0 || j >= 0) {
        int sum = carry;
        if (j >= 0) sum += s2.charAt(j--) - '0';
        if (i >= 0) sum += s1.charAt(i--) - '0';
        sb.append(sum % 2);
        carry = sum / 2;
    }
    if (carry != 0) sb.append(carry);
    return sb.reverse().toString();
}
akuriako
  • 429
  • 5
  • 7
2
public class BinaryArithmetic {

    /*-------------------------- add ------------------------------------------------------------*/
    static String add(double a, double b) {
        System.out.println(a + "first val :" + b);
        int a1 = (int) a;
        int b1 = (int) b;
        String s1 = Integer.toString(a1);
        String s2 = Integer.toString(b1);
        int number0 = Integer.parseInt(s1, 2);
        int number1 = Integer.parseInt(s2, 2);

        int sum = number0 + number1;
        String s3 = Integer.toBinaryString(sum);

        return s3;
    }
    /*-------------------------------multiply-------------------------------------------------------*/

    static String multiply(double a, double b) {
        System.out.println(a + "first val :" + b);
        int a1 = (int) a;
        int b1 = (int) b;
        String s1 = Integer.toString(a1);
        String s2 = Integer.toString(b1);
        int number0 = Integer.parseInt(s1, 2);
        int number1 = Integer.parseInt(s2, 2);

        int sum = number0 * number1;
        String s3 = Integer.toBinaryString(sum);

        return s3;
    }
    /*----------------------------------------substraction----------------------------------------------*/

    static String sub(double a, double b) {
        System.out.println(a + "first val :" + b);
        int a1 = (int) a;
        int b1 = (int) b;
        String s1 = Integer.toString(a1);
        String s2 = Integer.toString(b1);
        int number0 = Integer.parseInt(s1, 2);
        int number1 = Integer.parseInt(s2, 2);

        int sum = number0 - number1;
        String s3 = Integer.toBinaryString(sum);

        return s3;
    }

    /*--------------------------------------division------------------------------------------------*/
    static String div(double a, double b) {
        System.out.println(a + "first val :" + b);
        int a1 = (int) a;
        int b1 = (int) b;
        String s1 = Integer.toString(a1);
        String s2 = Integer.toString(b1);
        int number0 = Integer.parseInt(s1, 2);
        int number1 = Integer.parseInt(s2, 2);

        int sum = number0 / number1;
        String s3 = Integer.toBinaryString(sum);

        return s3;
    }
}
cheesemacfly
  • 11,622
  • 11
  • 53
  • 72
monir
  • 21
  • 1
2

Another interesting but long approach is to convert each of the two numbers to decimal, adding the decimal numbers and converting the answer obtained back to binary!

2

Java solution

static String addBinary(String a, String b) {

    int lenA = a.length();
    int lenB = b.length();
    int i = 0;

    StringBuilder sb = new StringBuilder();
    int rem = Math.abs(lenA-lenB);
    while(rem >0){
        sb.append('0');
        rem--;
    }
    if(lenA > lenB){
        sb.append(b);  
        b = sb.toString();
    }else{
        sb.append(a);
        a = sb.toString();
    }

    sb = new StringBuilder();
    char carry = '0';
    i = a.length();
    while(i > 0){
        if(a.charAt(i-1) == b.charAt(i-1)){
            sb.append(carry);
            if(a.charAt(i-1) == '1'){
                carry = '1';
            }else{
                carry = '0';
            }
        }else{
            if(carry == '1'){
                sb.append('0');
                carry = '1';
            }else{
                carry = '0';
                sb.append('1');
            }
        }
        i--;
    }

    if(carry == '1'){
        sb.append(carry);
    }

    sb.reverse();
    return sb.toString();

}
Shubham
  • 434
  • 6
  • 12
2
public String addBinary(String a, String b) { 
    int carry = 0;
    StringBuilder sb = new StringBuilder();
    for(int i = a.length() - 1, j = b.length() - 1;i >= 0 || j >= 0;i--,j--){
        int sum = carry + (i >= 0 ? a.charAt(i) - '0':0) + (j >= 0 ? b.charAt(j) - '0' : 0);
        sb.append(sum%2);
        carry =sum / 2;
    }
    if(carry > 0) sb.append(carry);
    sb.reverse();
    return sb.toString();
}
1

I've actually managed to find a solution to this question without using the stringbuilder() function. Check this out:

public void BinaryAddition(String s1,String s2)
{
    int l1=s1.length();int c1=l1;
    int l2=s2.length();int c2=l2;
    int max=(int)Math.max(l1,l2);
    int arr1[]=new int[max];
    int arr2[]=new int[max];
    int sum[]=new int[max+1];
    for(int i=(arr1.length-1);i>=(max-l1);i--)
    {
        arr1[i]=(int)(s1.charAt(c1-1)-48);
        c1--;
    }
    for(int i=(arr2.length-1);i>=(max-l2);i--)
    {
        arr2[i]=(int)(s2.charAt(c2-1)-48);
        c2--;
    }
    for(int i=(sum.length-1);i>=1;i--)
    {
        sum[i]+=arr1[i-1]+arr2[i-1];
        if(sum[i]==2)
        {
            sum[i]=0;
            sum[i-1]=1;
        }
        else if(sum[i]==3)
        {
            sum[i]=1;
            sum[i-1]=1;
        }
    }
    int c=0;
    for(int i=0;i<sum.length;i++)
    {
        System.out.print(sum[i]);
    }
}
spenibus
  • 4,339
  • 11
  • 26
  • 35
BongCoder
  • 11
  • 1
1

The idea is same as discussed in few of the answers, but this one is a much shorter and easier to understand solution (steps are commented).

// Handles numbers which are way bigger.
public String addBinary(String a, String b) {
    StringBuilder sb = new StringBuilder();
    int i = a.length() - 1; 
    int j = b.length() -1;
    int carry = 0;
    while (i >= 0 || j >= 0) {
        int sum = carry;
        if (j >= 0) { sum += b.charAt(j--) - '0' };
        if (i >= 0) { sum += a.charAt(i--) - '0' };

        // Added number can be only 0 or 1
        sb.append(sum % 2);

        // Get the carry.
        carry = sum / 2;
    }

    if (carry != 0) { sb.append(carry); }

    // First reverse and then return.
    return sb.reverse().toString();
}
Pritam Banerjee
  • 17,953
  • 10
  • 93
  • 108
0

i tried to make it simple this was sth i had to deal with with my cryptography prj its not efficient but i hope it

    public String binarysum(String a, String b){
    int carry=0;
    int maxim;
    int minim;
    maxim=Math.max(a.length(),b.length());
    minim=Math.min(a.length(),b.length());         
    char smin[]=new char[minim];
    char smax[]=new char[maxim];
    if(a.length()==minim){
     for(int i=0;i<smin.length;i++){
     smin[i]=a.charAt(i);
      }
      for(int i=0;i<smax.length;i++){
       smax[i]=b.charAt(i);
      }
      }
      else{
          for(int i=0;i<smin.length;i++){
          smin[i]=b.charAt(i);
             }
       for(int i=0;i<smax.length;i++){
       smax[i]=a.charAt(i);
      } 
      }
    char[]sum=new char[maxim];
    char[] st=new char[maxim];
    for(int i=0;i<st.length;i++){
    st[i]='0';
    }
    int k=st.length-1;
   for(int i=smin.length-1;i>-1;i--){
    st[k]=smin[i];
    k--;
    } 

     //   *************************** sum begins here
   for(int i=maxim-1;i>-1;i--){
   char x= smax[i];
   char y= st[i];
    if(x==y && x=='0'){
         if(carry==0)
             sum[i]='0';
         else if(carry==1){
             sum[i]='1';
             carry=0;
    }
   }
    else if(x==y && x=='1'){
        if(carry==0){
            sum[i]='0';
            carry=1;
        }
        else if(carry==1){
          sum[i]='1';
          carry=1;
        }
     }
     else if(x!=y){
        if(carry==0){
            sum[i]='1';
            }
        else if(carry==1){
          sum[i]='0';
          carry=1;
        }
       }        }
      String s=new String(sum);
     return s;
      }
0
class Sum{
    public int number;
    public int carry;

    Sum(int number, int carry){
        this.number = number; 
        this.carry = carry;
    }
}

public String addBinary(String a, String b) {

    int lengthOfA = a.length();
    int lengthOfB = b.length();

    if(lengthOfA > lengthOfB){
        for(int i=0; i<(lengthOfA - lengthOfB); i++){
            b="0"+b;
        }
    }
    else{
         for(int i=0; i<(lengthOfB - lengthOfA); i++){
            a="0"+a;
        }
    }

    String result = "";
    Sum s = new Sum(0,0);
    for(int i=a.length()-1; i>=0; i--){
        s = addNumber(Character.getNumericValue(a.charAt(i)), Character.getNumericValue(b.charAt(i)), s.carry);
        result = result + Integer.toString(s.number);
    }

    if(s.carry == 1) { result += s.carry ;}

    return new StringBuilder(result).reverse().toString();
}

Sum addNumber(int number1, int number2, int carry){
        Sum sum = new Sum(0,0);
        sum.number = number1 ^ number2 ^ carry;
        sum.carry = (number1 & number2) | (number2 & carry) | (number1 & carry);

        return sum;
}
0
import java.util.*;
public class BitAddition {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner sc = new Scanner(System.in);
        int len = sc.nextInt();
        int[] arr1 = new int[len];
        int[] arr2 = new int[len];
        int[] sum = new int[len+1];
        Arrays.fill(sum, 0);
        for(int i=0;i<len;i++){
            arr1[i] =sc.nextInt();
        }
        for(int i=0;i<len;i++){
            arr2[i] =sc.nextInt();
        }
        for(int i=len-1;i>=0;i--){
            if(sum[i+1] == 0){
                if(arr1[i]!=arr2[i]){
                    sum[i+1] = 1;
                }
                else if(arr1[i] ==1 && arr2[i] == 1){
                    sum[i+1] =0 ;
                    sum[i] = 1;
                }
            }
            else{
                if((arr1[i]!=arr2[i])){
                    sum[i+1] = 0;
                    sum[i] = 1;
                }
                else if(arr1[i] == 1){
                    sum[i+1] = 1;
                    sum[i] = 1;
                }
            }
        }
        for(int i=0;i<=len;i++){

        System.out.print(sum[i]);
        }
    }

}
Grainier
  • 1,634
  • 2
  • 17
  • 30
Subrat Sahu
  • 71
  • 1
  • 6
0

One of the simple ways is as:

  1. convert the two strings to char[] array and set carry=0.
  2. set the smallest array length in for loop
  3. start for loop from the last index and decrement it
  4. check 4 conditions(0+0=0, 0+1=1, 1+0=1, 1+1=10(carry=1)) for binary addition for each element in both the arrays and reset the carry accordingly.
  5. append the addition in stringbuffer
  6. append rest of the elements from max size array to stringbuffer but check consider carry while appending
  7. print stringbuffer in reverse order for the answer.

//The java code is as

static String binaryAdd(String a, String b){
    int len = 0;
    int size = 0;
    char[] c1 = a.toCharArray();
    char[] c2 = b.toCharArray();
    char[] max;


    if(c1.length > c2.length){
        len = c2.length;
        size = c1.length;
        max = c1;
    }       
    else
    {
        len = c1.length;
        size = c2.length;
        max = c2;
    }

    StringBuilder sb = new StringBuilder();
    int carry = 0;
    int p = c1.length - 1;
    int q = c2.length - 1;

    for(int i=len-1; i>=0; i--){
        if(c1[p] == '0' && c2[q] == '0'){
            if(carry == 0){
                sb.append(0);
                carry = 0;
            }   
            else{
                sb.append(1);
                carry = 0;
            }   
        }
        if((c1[p] == '0' && c2[q] == '1') || (c1[p] == '1' && c2[q] == '0')){
            if(carry == 0){
                sb.append(1);
                carry = 0;
            }   
            else{
                sb.append(0);
                carry = 1;
            }                   
        }
        if((c1[p] == '1' && c2[q] == '1')){
            if(carry == 0){
                sb.append(0);
                carry = 1;
            }   
            else{
                sb.append(1);
                carry = 1;
            }
        }
        p--;
        q--;
    }

    for(int j = size-len-1; j>=0; j--){
        if(max[j] == '0'){ 
            if(carry == 0){     
                sb.append(0);
                carry = 0;
            }   
            else{
                sb.append(1);
                carry = 0;
            }   
        }
        if(max[j] == '1'){
            if(carry == 0){     
                sb.append(1);
                carry = 0;
            }   
            else{
                sb.append(0);
                carry = 1;
            }   
        }           
    }
    if(carry == 1)
        sb.append(1);   
    return sb.reverse().toString();
}
Nik's
  • 21
  • 4
0
import java.io.; 
import java.util.; 
public class adtbin {
  static Scanner sc=new Scanner(System.in); 
   public void fun(int n1) {
      int i=0; 
      int sum[]=new int[20]; 
      while(n1>0) { 
        sum[i]=n1%2; n1=n1/2; i++; 
      } 
      for(int a=i-1;a>=0;a--) { 
          System.out.print(sum[a]); 
      }  
   } 
   public static void main() { 
     int m,n,add; 
     adtbin ob=new adtbin(); 
     System.out.println("enter the value of m and n"); 
     m=sc.nextInt(); 
     n=sc.nextInt(); 
     add=m+n; 
     ob.fun(add); 
   } 
}
Kiran
  • 20,167
  • 11
  • 67
  • 99
james
  • 1
  • a bit of explanation is welcome with code. code only answers might be flagged as "low quality" and removed, even if they are technically valid. – Gilles Gouaillardet Sep 16 '17 at 05:19
0

you can write your own One.

long a =100011111111L;
long b =1000001111L;

int carry = 0 ;
long result = 0;

long multiplicity = 1;

while(a!=0 || b!=0 || carry ==1){
    if(a%10==1){
        if(b%10==1){
            result+= (carry*multiplicity);
            carry = 1;
        }else if(carry == 1){
            carry = 1;  
        }else{
            result += multiplicity;
        }
    }else if (b%10 == 1){
        if(carry == 1){
            carry = 1;
        }else {
            result += multiplicity; 
        }
    }else {
        result += (carry*multiplicity);
        carry = 0;
    }

    a/=10;
    b/=10;
    multiplicity *= 10;

}


System.out.print(result);

it works just by numbers , no need string , no need SubString and ...

e.hadid
  • 999
  • 9
  • 20
0
package Assignment19thDec;

import java.util.Scanner;

public class addTwoBinaryNumbers {

    private static Scanner sc;

    public static void main(String[] args) {

        sc = new Scanner(System.in);
        System.out.println("Enter 1st Binary Number");
        int number1=sc.nextInt();
        int reminder1=0;
        int number2=sc.nextInt();
        int reminder2=0;
        int carry=0;
        double sumResult=0 ;int add = 0
        ;
        int n;
        int power=0;
        while (number1>0 || number2>0) {

            /*System.out.println(number1 + " " +number2);*/

            reminder1=number1%10;
            number1=number1/10;
            reminder2=number2%10;
            number2=number2/10;
            /*System.out.println(reminder1 +"  "+ reminder2);*/


            if(reminder1>1 || reminder2>1 ) {
                System.out.println("not a binary number");
                System.exit(0);
            }

            n=reminder1+reminder2+carry;
            switch(n) {

            case 0: 
                    add=0; carry=0;                                 
                    break;                  
            case 1: add=1; carry=0;
                    break;
            case 2: add=0; carry=1;
                    break;
            case 3: add=1;carry=1;
                    break;
            default: System.out.println("not a binary number ");

            }

            sumResult=add*(Math.pow(10, power))+sumResult;
            power++;


        }

        sumResult=carry*(Math.pow(10, power))+sumResult;
        System.out.println("\n"+(int)sumResult);


    }

}
Valerica
  • 1,618
  • 1
  • 13
  • 20
0
Try this, tested with binary and decimal and its self explanatory

public String add(String s1, String s2, int radix){
        int s1Length = s1.length();
        int s2Length = s2.length();
        int reminder = 0;
        int carry = 0;
        StringBuilder result = new StringBuilder();
        int i = s1Length -1;
        int j = s2Length -1;
        while (i >=0 && j>=0) {
            int operand1 = Integer.valueOf(s1.charAt(i)+"");
            int operand2 = Integer.valueOf(s2.charAt(j)+"");
            reminder = (operand1+operand2+carry) % radix;
            carry = (operand1+operand2+carry) / radix;
            result.append(reminder);
            i--;j--;
        }
        while(i>=0){
            int operand1 = Integer.valueOf(s1.charAt(i)+"");
            reminder = (operand1+carry) % radix;
            carry = (operand1+carry) / radix;
            result.append(reminder);
            i--;
        }
        while(j>=0){
            int operand1 = Integer.valueOf(s2.charAt(j)+"");
            reminder = (operand1+carry) % radix;
            carry = (operand1+carry) / radix;
            result.append(reminder);
            j--;
        }
        return result.reverse().toString();
    }
}
balusu48
  • 1
  • 1
0
static int addBinaryNumbers(String a, String b) {
    int firstToDecimal = 0;
    int secondToDecimal = 0;
    for (int i = a.length() - 1, count = 0; i >= 0; i--, count++) {
        firstToDecimal += (Math.pow(2, count) * Integer.parseInt(String.valueOf(a.toCharArray()[i])));

    }
    for (int i = b.length() - 1, count = 0; i >= 0; i--, count++) {
        secondToDecimal += (Math.pow(2, count) * Integer.parseInt(String.valueOf(b.toCharArray()[i])));

    }
    return firstToDecimal + secondToDecimal;
}

public static void main(String[] args) {
    System.out.println(addBinaryNumbers("101", "110"));

}
Abel Kibebe
  • 39
  • 1
  • 7
-1

here's a python version that

def binAdd(s1, s2):
    if not s1 or not s2:
        return ''

    maxlen = max(len(s1), len(s2))


    s1 = s1.zfill(maxlen)
    s2 = s2.zfill(maxlen)

    result  = ''
    carry   = 0

    i = maxlen - 1
    while(i >= 0):
        s = int(s1[i]) + int(s2[i])
        if s == 2: #1+1
            if carry == 0:
                carry = 1
                result = "%s%s" % (result, '0')
            else:
                result = "%s%s" % (result, '1')
        elif s == 1: # 1+0
            if carry == 1:
                result = "%s%s" % (result, '0')
            else:
                result = "%s%s" % (result, '1')
        else: # 0+0
            if carry == 1:
                result = "%s%s" % (result, '1')
                carry = 0   
            else:
                result = "%s%s" % (result, '0') 

        i = i - 1;

    if carry>0:
        result = "%s%s" % (result, '1')
    return result[::-1]
Algorithmatic
  • 1,824
  • 2
  • 24
  • 41
-2
import java.util.Scanner;
{
    public static void main(String[] args) 
    {
        String b1,b2;
        Scanner sc= new Scanner(System.in);
        System.out.println("Enter 1st binary no. : ") ;
        b1=sc.next();
        System.out.println("Enter 2nd binary no. : ") ;
        b2=sc.next();
        int num1=Integer.parseInt(b1,2);
        int num2=Integer.parseInt(b2,2);
        int sum=num1+num2;
        System.out.println("Additon is : "+Integer.toBinaryString(sum));
    }

}