Adding binary numbers

后端 未结 21 1129
孤独总比滥情好
孤独总比滥情好 2020-11-28 07:50

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

For example, 1010 + 10 = 1100.

相关标签:
21条回答
  • 2020-11-28 08:08

    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();
    }
    
    0 讨论(0)
  • 2020-11-28 08:09
    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 讨论(0)
  • 2020-11-28 08:10

    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]
    
    0 讨论(0)
  • 2020-11-28 08:11

    Martijn is absolutely correct, to piggyback and complete the answer

    Integer.toBinaryString(sum);
    

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

    0 讨论(0)
  • 2020-11-28 08:12

    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();
    }
    
    0 讨论(0)
  • 2020-11-28 08:17
    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); 
       } 
    }
    
    0 讨论(0)
提交回复
热议问题