Kotlinlearncs.online LogoJava
Return to List

Solve: Decimal to Binary String

Created By: Rohith Sanjay
/ Version: 2024.9.1

Write a method binaryString that accepts 1 argument: an Int. This Int will be a positive decimal integer (0 to 2147483647 inclusive). Your method must convert this input to binary form. Because binary representations often use many more characters compared to decimal form, and Ints have a maximum value, your method should return this binary number in String form.

As a refresher, a binary number uses 1s and 0s, with the least significant digit (right most) representing 2^0 (1), and the most significant digit (left most) representing the largest power of 2 that is less than or equal to the input integer.

For example, the binary form of 0 is 0, the binary form of 1 is 1, the binary form of 5 is 101 (1 on the right side represents 2^0, and 1 on the left side represents 2^2, and 2^1 is skipped as the middle is 0; 2^0 + 2^2 = 5). The output string should NOT include leading zeros and should NOT include any prefix like "0b". So if we call binaryString(12), your method will return "1100" (NOT "01100"). Please make sure you understand what binary representation is before doing this problem.

There are many ways to approach this problem. It's recommended to use a loop and add one character ("1" or "0") to the string at a time.

Related Lessons

Stuck? You may find these lessons helpful:

Report a Problem

Attribution must link to this page: https://www.learncs.online/solve/kotlin/decimal-to-binary-string/[email protected]