Simple Java Solution


  • 0
    R
        public String addBinary(String a, String b) {
          String str = "";
          int carry = 0;
          int max = Math.max(a.length(), b.length());
          int min = Math.min(a.length(), b.length());
          int diff = max - min;
    
          if(a.length() != b.length()) {
              
          if(a.length() == max) {
              while(diff != 0) {
                  b = "0" + b;
                  diff--;
              }
          } else if(b.length() == max) {
              while(diff != 0) {
                  a = "0" + a;
                  diff--;
              }
          }
          
          }
          
          for(int i = max-1; i >= 0; i--) {
              int x = 0;
              int y = 0;
              
              
              x = Integer.parseInt(String.valueOf(a.charAt(i)));
              y = Integer.parseInt(String.valueOf(b.charAt(i)));
              
     
              str = String.valueOf(carry ^ (x ^ y)) + str;
              if((x + y + carry) > 1) {
                  carry = 1;
              } else {
                  carry = 0;
              }
          }
          
          if(carry == 1) {
              str = "1" + str;
          }
          
          
          
          return str;
        }
    }

Log in to reply
 

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