Show problems as
Classic problem #67EasyMathStringBit ManipulationSimulation

Add Binary

Real-world version: Combined Toggle Row
Tracked in this browser only
Read Add Binary on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

A test rig has two long rows of toggle switches. A row is recorded as a string of the characters '0' and '1', one character per switch, the most significant switch written first, and the row is read as a count in base two. A recorded row never opens with '0' unless the whole row is the single character '0'.

Given the recorded rows top and bottom, return the row that would show their combined count. Use the same format: base two, most significant switch first, and no opening '0' unless the combined count is zero, in which case the answer is the single character '0'.

A row can hold far more switches than the rig's registers can count, so settle the columns one at a time from the least significant switch, carrying into the next column, rather than reading a whole row into a single number.

Examples

Example 1

Input
top = "1011", bottom = "110"
Output
"10001"

The rows stand for eleven and six, and the seventeen they combine to is written 10001 in base two.

Example 2

Input
top = "10011", bottom = "1101"
Output
"100000"

The rows stand for nineteen and thirteen, and the thirty-two they combine to is written 100000 in base two.

Example 3

Input
top = "0", bottom = "1001"
Output
"1001"

The top row is zero, so the combined count matches the bottom row and is written the same way.

Constraints

  • 1 <= top.length, bottom.length <= 10^4
  • top and bottom hold only the characters '0' and '1'
  • Neither row opens with '0' unless it is the single character '0'

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def combine_toggle_rows(top: str, bottom: str) -> str:
Java
public String combineToggleRows(String top, String bottom)