Java AddBinary Tes Case 194


  • 0
    J

    public class Solution {

    public String addBinary(String a, String b) {
        int alen = a.length();
        int blen = b.length();
        
        int aval = 0;
        int bval = 0;
        int total = 0;
        
        for(int n=alen-1, mul=0; n>=0; n--, mul++){
            aval += (a.charAt(n)-'0')*Math.pow(2, mul);
        }
        
        for(int n=blen-1, mul=0; n>=0; n--, mul++){
            bval += (b.charAt(n)-'0')*Math.pow(2, mul);
        }
        
        total = aval + bval;
        
        if(total==0){
            return "0";
        }
        
        String result = "";
        
        while(total!=0){
            int current = total/2;
            int rem = total%2;
            result = rem + result;
            total = current;
        }
        
        return result;
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.