{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "

67. Add Binary

\n", "
\n", "\n", "\n", "

Given two binary strings a and b, return their sum as a binary string.

\n", "\n", "

 

\n", "

Example 1:

\n", "
Input: a = \"11\", b = \"1\"\n",
    "Output: \"100\"\n",
    "

Example 2:

\n", "
Input: a = \"1010\", b = \"1011\"\n",
    "Output: \"10101\"\n",
    "
\n", "

 

\n", "

Constraints:

\n", "\n", "\n", "\n", "\n", "

 

\n", "Source \n", "
\n", "\n", "

Code

" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "def add_binary(a, b):\n", " \"\"\"Cheating method.\"\"\"\n", " return bin(int(a, 2) + int(b, 2))[2:] # int('s', n) --> convert 's' into number base n" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "def add_binary(a, b):\n", " pos1 = len(a)-1\n", " pos2 = len(b)-1\n", " carry = 0\n", " result = \"\"\n", " while carry or pos1 >= 0 or pos2 >= 0:\n", " s1 = 0 if pos1 < 0 else int(a[pos1])\n", " s2 = 0 if pos2 < 0 else int(b[pos2])\n", " result += str((s1 + s2 + carry) % 2)\n", " carry = (s1 + s2 + carry) // 2\n", " pos1 -= 1\n", " pos2 -= 1\n", " return result[::-1]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "

Check

" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'100'" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a = \"11\"\n", "b = \"1\"\n", "add_binary(a, b)" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'10101'" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a = \"1010\"\n", "b = \"1011\"\n", "add_binary(a, b)" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'1100'" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a = \"1\"\n", "b = \"1011\"\n", "add_binary(a, b)" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.8.2" } }, "nbformat": 4, "nbformat_minor": 1 }