Skip to content

Latest commit

 

History

History
60 lines (47 loc) · 1.67 KB

67 Add Binary 82e532c8c101469eb790bb517448c9f7.md

File metadata and controls

60 lines (47 loc) · 1.67 KB

67. Add Binary

LeetCode - The World's Leading Online Programming Learning Platform

class Solution {
   public static String addBinary(String a, String b) {
    int carry = 0;
    StringBuilder output = new StringBuilder();
    int length = Math.max(a.length(), b.length());

    for (int i = a.length() - 1, z = b.length() - 1; length > 0; i--, z--, length--) {
        int x = (i >= 0) ? Character.getNumericValue(a.charAt(i)) : 0;
        int y = (z >= 0) ? Character.getNumericValue(b.charAt(z)) : 0;

        int sum = x + y + carry;
        output.append(sum % 2); // Append the remainder of the sum
        carry = sum / 2; // Update the carry
    }

    if (carry > 0) {
        output.append(carry); // If there's a final carry, append it
    }

    return output.reverse().toString();
}

}
class Solution {
public static String addBinary(String a, String b) {
    int carry = 0;
    StringBuilder output = new StringBuilder();
    int length = Math.max(a.length(), b.length()); // Use Math.max to get the maximum length

    for (int i = a.length() - 1, z = b.length() - 1; length > 0; i--, z--, length--) {
        int x = (i >= 0) ? Character.getNumericValue(a.charAt(i)) : 0;
        int y = (z >= 0) ? Character.getNumericValue(b.charAt(z)) : 0;

        int sum = x + y + carry;

        if (sum > 1) {
            carry = 1;
            output.append(sum % 2); // Append the remainder of the sum
        } else {
            carry = 0;
            output.append(sum);
        }
    }

    if (carry > 0) {
        output.append(carry); // If there's a final carry, append it
    }

    return output.reverse().toString();
}
}