Add Binary
Updated
Problem statement
You are given two binary strings a and b, each the binary form of a non-negative integer. Return their sum, also as a binary string.
The answer must not have leading zeros, except that a sum of zero is written as "0". The numbers can be far longer than 64 bits.
Function
addBinary(a: String, b: String) → StringExamples
Example 1
a = "1011"b = "110"return = "10001"In decimal this is 11 + 6 = 17, and 17 in binary is 10001. Column by column from the right: 1+0=1; 1+1=10 (write 0, carry 1); 0+1+1=10 (write 0, carry 1); 1+0+1=10 (write 0, carry 1); and the last carry gives the leading 1.
Example 2
a = "0"b = "0"return = "0"0 + 0 = 0, written as the single digit 0.
Example 3
a = "1"b = "111"return = "1000"1 + 7 = 8, which is 1000 in binary: the carry runs through every digit and adds one new digit at the front.
Constraints
1 <= a.length, b.length <= 10^4aandbconsist only of the characters0and1.- Neither string has leading zeros, except the string
"0"itself.
More Microsoft Onsite Interview questions
- Longest Substring Without Repeating CharactersONSITE INTERVIEW · Seen Nov 2026
- Valid ParenthesesONSITE INTERVIEW · Seen Nov 2026
- Count a User's Actions in an Event LogONSITE INTERVIEW · Seen Nov 2026
- Smallest Batch Size Within a Step LimitONSITE INTERVIEW · Seen Nov 2026
- Count Subarrays with Equal Even and Odd CountsONSITE INTERVIEW · Seen Nov 2026
- Minimum Time to Rot All OrangesONSITE INTERVIEW · Seen Nov 2026
- Coin ChangeONSITE INTERVIEW · Seen Oct 2026
- Daily USD Totals with Effective-Dated Exchange RatesONSITE INTERVIEW · Seen Oct 2026
- Number Words to Digits in Any LanguageONSITE INTERVIEW · Seen Oct 2026
- Totals from a Tiered Rate TableONSITE INTERVIEW · Seen Oct 2026
Similar questions at other companies
- Add Two Binary StringsPeopleStrong · ONSITE INTERVIEWPeopleStrong interview questions
- Count Times Using at Most Two DigitsLSEG · OALSEG interview questions
- Roman to IntegerKotak Mahindra Bank · PHONE SCREEN · ONSITE INTERVIEWKotak Mahindra Bank interview questions
- Find the Missing Number from 1 to nHyperVerge · ONSITE INTERVIEW
- Palindrome Match PercentageApple · ONSITE INTERVIEWApple interview questions
- Swap Two Integers Without a Temporary VariableOracle · ONSITE INTERVIEWOracle interview questions
- Caesar Cipher with a Precomputed AlphabetAmazon · ONSITE INTERVIEW
- Most Cost-Effective MachineCapital One · ONSITE INTERVIEWCapital One interview questions
- Check Whether a Byte Is NonzeroZscaler · ONSITE INTERVIEWZscaler interview questions
- Add Two Numeric Strings with CarryZipRecruiter · ONSITE INTERVIEWZipRecruiter interview questions