My java 5ms solution


  • 0
    D
    public class Solution {
        public String addBinary(String a, String b) {
            if (a == null || b == null) {
                return null;
            }
            int n = a.length();
            int m = b.length();
            String longS = a.length() >= b.length() ? a : b;
            String shortS = a.length() < b.length() ? a : b;
            int[] res = new int[longS.length() + 1];
            int carry = 0;
            for (int i = 0; i < longS.length(); ++i) {
                int cur1 = 0;
                int cur2 = longS.charAt(longS.length() - 1 - i) - '0';
                if (i < shortS.length()) cur1 = shortS.charAt(shortS.length() - 1 - i) - '0';
                int sum = cur1 + cur2 + carry;
                int digit = sum % 2;
                carry = sum / 2;
                res[res.length - 1 - i] = digit;
            }
            if (carry > 0) {
                res[0] = carry;
            }
            StringBuilder sb = new StringBuilder();
            for (int j = 0; j < res.length; ++j) {
                if (!(sb.length() == 0 && res[j] == 0)) {
                    sb.append(res[j]);
                }
            }
            return sb.length() == 0 ? "0" : sb.toString();
        }
    }
    

Log in to reply
 

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