Files
wehub-resource-sync dde272c4b8
i18n - Build Validation / Validate i18n Builds (24) (push) Has been cancelled
CI - Node.js / Lint (24) (push) Has been cancelled
CI - Node.js / Build (24) (push) Has been cancelled
CI - Node.js / Test (24) (push) Has been cancelled
CI - Node.js / Test - Upcoming Changes (24) (push) Has been cancelled
CI - Node.js / Test - i18n (italian, 24) (push) Has been cancelled
CI - Node.js / Test - i18n (portuguese, 24) (push) Has been cancelled
CD - Docker - GHCR Images / Build and Push Images (push) Has been cancelled
chore: import upstream snapshot with attribution
2026-07-13 11:55:53 +08:00

1.6 KiB

id, title, challengeType, dashedName
id title challengeType dashedName
68b7cadffed0e75a517da675 Challenge 53: Decimal to Binary 29 challenge-53

--description--

Given a non-negative integer, return its binary representation as a string.

A binary number uses only the digits 0 and 1 to represent any number. To convert a decimal number to binary, repeatedly divide the number by 2 and record the remainder. Repeat until the number is zero. Read the remainders last recorded to first. For example, to convert 12 to binary:

12 ÷ 2 = 6 remainder 0
6 ÷ 2 = 3 remainder 0
3 ÷ 2 = 1 remainder 1
1 ÷ 2 = 0 remainder 1

12 in binary is 1100.

--hints--

to_binary(5) should return "101".

({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(to_binary(5), "101")`)
}})

to_binary(12) should return "1100".

({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(to_binary(12), "1100")`)
}})

to_binary(50) should return "110010".

({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(to_binary(50), "110010")`)
}})

to_binary(99) should return "1100011".

({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(to_binary(99), "1100011")`)
}})

--seed--

--seed-contents--

def to_binary(decimal):

    return decimal

--solutions--

def to_binary(decimal):
    if decimal == 0:
        return "0"
    binary = ""
    while decimal > 0:
        binary = str(decimal % 2) + binary
        decimal //= 2
    return binary