All Downloads are FREE. Search and download functionalities are using the official Maven repository.

g0001_0100.s0067_add_binary.Solution Maven / Gradle / Ivy

There is a newer version: 1.38
Show newest version
package g0001_0100.s0067_add_binary;

// #Easy #String #Math #Bit_Manipulation #Simulation #Programming_Skills_II_Day_5
// #2023_08_11_Time_1_ms_(100.00%)_Space_41.6_MB_(36.86%)

/**
 * 67 - Add Binary\.
 *
 * Easy
 *
 * Given two binary strings `a` and `b`, return _their sum as a binary string_.
 *
 * **Example 1:**
 *
 * **Input:** a = "11", b = "1"
 *
 * **Output:** "100" 
 *
 * **Example 2:**
 *
 * **Input:** a = "1010", b = "1011"
 *
 * **Output:** "10101" 
 *
 * **Constraints:**
 *
 * *   1 <= a.length, b.length <= 104
 * *   `a` and `b` consist only of `'0'` or `'1'` characters.
 * *   Each string does not contain leading zeros except for the zero itself.
**/
public class Solution {
    public String addBinary(String a, String b) {
        char[] aArray = a.toCharArray();
        char[] bArray = b.toCharArray();
        StringBuilder sb = new StringBuilder();
        int i = aArray.length - 1;
        int j = bArray.length - 1;
        int carry = 0;
        while (i >= 0 || j >= 0) {
            int sum = (i >= 0 ? aArray[i] - '0' : 0) + (j >= 0 ? bArray[j] - '0' : 0) + carry;
            sb.append(sum % 2);
            carry = sum / 2;
            if (i >= 0) {
                i--;
            }
            if (j >= 0) {
                j--;
            }
        }
        if (carry != 0) {
            sb.append(carry);
        }
        return sb.reverse().toString();
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy