My Simple and Easy Understand Solution


  • 0
    Y

    My Java Simple and Easy Solution

    Each character is decide by a char in string a and a char in string b and the carry (previously added results)

    public class Solution {
        public String addBinary(String a, String b) {
          StringBuilder sb = new StringBuilder();
          int count = 0;
          int carry = 0;
          int ac = 0;
          int bc = 0;
          int al = a.length();
          int bl = b.length();  
          while (carry > 0 || count < al || count < bl) {
            if (count < al && a.charAt(al - 1 - count) == '1') {
              ac = 1;    
            } else {
              ac = 0;  
            }  
            if (count < bl && b.charAt(bl - 1 - count) == '1') {
              bc = 1;    
            } else {
              bc = 0;  
            } 
            int sum = (ac + bc + carry) % 2; 
            sb.insert(0, sum); 
            carry = (ac + bc + carry) / 2; 
            count++;  
          } 
          return sb.toString();  
        }
    }
    

Log in to reply
 

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