LeetCode Entry

67. Add Binary

15.02.2026 easy 2026 kotlin rust

Binary strings sum

67. Add Binary easy blog post substack youtube

63029afe-a537-444e-8e13-0761c7dbdc2a (1).webp

Join me on Telegram

https://t.me/leetcode_daily_unstoppable/1269

Problem TLDR

Binary strings sum #easy

Intuition

Carry = value / base

Approach

  • ‘0’ = 48, so &1 converts char to 1 or 0
  • insert(0) is O(n^2) but only 9ms for the test cases

Complexity

  • Time complexity: \(O(n)\)

  • Space complexity: \(O(n)\)

Code

// 9ms
    fun addBinary(a: String, b: String) = buildString {
        var c = 0; var i = a.lastIndex; var j = b.lastIndex
        while (i >= 0 || j >= 0 || c > 0) {
            c += if (i < 0) 0 else a[i--]-'0'
            c += if (j < 0) 0 else b[j--]-'0'
            insert(0, c % 2); c /= 2
        }
    }
// 0ms
    pub fn add_binary(a: String, b: String) -> String {
        let (mut a, mut b, mut c) = (a.bytes().rev(), b.bytes().rev(), 0);
        from_fn(|| (a.len() > 0 || b.len() > 0 || c > 0).then(|| {
            c += (a.next().unwrap_or(0)&1) + (b.next().unwrap_or(0)&1);
            let v = c % 2 + 48; c /= 2; v as char
        })).collect::<Vec<_>>().iter().rev().collect()
    }