Kotlinlearncs.online LogoJava
Return to List

Test Writing: 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.

Test Design Challenge

You're challenge is to write tests for this problem described above.

  • Provide a method named test that accepts no arguments and does not return a value.
  • If the implementation of the class described above is incorrect, your test method should throw an exception.
  • If it is correct, do not throw an exception.
  • You may want to use Java's assert method
Report a Problem

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