Adding binary numbers

后端 未结 21 1441
孤独总比滥情好
孤独总比滥情好 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:05

    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-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;
          }
    

提交回复
热议问题