Clear solution with explanation


  • 0
    K
    public class Solution {
    // acknowledge to http://www.jiuzhang.com/
        public String addBinary(String a, String b) {
            if(a.length() < b.length()){
                String temp = a;
                a = b;
                b = temp; // make sure that a is no shorter than b;
            }
            int pa = a.length() - 1;
            int pb = b.length() - 1;
            int c  = 0;
            String result = "";
            while(pb >= 0){
                int sum = (int)(a.charAt(pa) - '0') + (int)(b.charAt(pb) - '0') + c;
                result = String.valueOf(sum % 2) + result;
                // 1 + 0 or 0 + 1 both creates 1 as result and no carry-out;
                // 1 + 1 creates 0 and result
                c = sum / 2;  // and 1 as carry-out;
                pa--;
                pb--;
                // since b is no longer than a, first sum up this b part
                // now pb is 0 and exit the while loop, enter the next while loop 
                // for the higher part with (lengtha - lengthb);
            }
            while(pa >= 0){
                int sum = (int)(a.charAt(pa) - '0') + c;
                result = String.valueOf(sum % 2) + result;
                c = sum / 2;
                pa--;
            }
            if(c == 1) result = "1" + result; // if the last carry-out is 1, then need to // extend the string and add 1 at the highest digit
            return result;
        }
    }

Log in to reply
 

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