Content-Length: 9095 | pFad | https://leetcode-in-net.github.io/LeetCodeNet/G0001_0100/S0067_add_binary

LeetCode in Net | C#-based LeetCode algorithm problem solutions, regularly updated.

LeetCode in Net

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:

Solution

public class Solution {
    public string AddBinary(string a, string b) {
        var sb = new System.Text.StringBuilder();
        int i = a.Length - 1; 
        int j = b.Length - 1; 
        int carry = 0;
        while (i >= 0 || j >= 0 || carry > 0) {
            int sum = carry;
            if (i >= 0) {
                sum += a[i--] - '0';
            }
            if (j >= 0) {
                sum += b[j--] - '0';
            }
            sb.Insert(0, (char)('0' + (sum % 2)));
            carry = sum / 2;
        }
        return sb.ToString();
    }
}








ApplySandwichStrip

pFad - (p)hone/(F)rame/(a)nonymizer/(d)eclutterfier!      Saves Data!


--- a PPN by Garber Painting Akron. With Image Size Reduction included!

Fetched URL: https://leetcode-in-net.github.io/LeetCodeNet/G0001_0100/S0067_add_binary

Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy