+ 5

Binary Converter

The binary numeric system uses only two digits: 0 and 1. Computers operate in binary, meaning they store data and perform calculations using only zeros and ones. You need to make a program to convert integer numbers to their binary representation. Create a Converter class with a static toBinary() method, which returns the binary version of its argument. The code in main takes a number as input and calls the corresponding static method. Make sure the code works as expected. Sample Input: 42 Sample Output: 101010 You can use the following code to convert a number to binary: import java.util.Scanner; //your code goes here String binary=""; while (num > 0) { binary = (num%2)+binary; num /= 2; } public class Program { public static void main(String[ ] args) { Scanner sc = new Scanner(System.in); int x = sc.nextInt(); System.out.print(Converter.toBinary(x)); } } Here's the code that I have so far. What do i do from this point?

18th May 2021, 1:53 PM
William Tomah
William Tomah - avatar
5 odpowiedzi
+ 2
//your code goes here public class Converter { public static String toBinary(int n) { String output = ""; if (n >= 1) { output = toBinary(n >> 1) + (n % 2); } return output; } }
8th Feb 2022, 9:46 AM
Asma Merabet
+ 1
public class Converter { public static String toBinary(int n) { String output = ""; if (n >= 1) { output = toBinary(n >> 1) + (n % 2); } return output; } }
2nd May 2022, 9:39 AM
MAHESH
MAHESH - avatar
+ 1
ok ok ok: import java.util.Scanner; public class Converter { public static String toBinary(int num) { String binary=""; while(num > 0) { binary = (num%2)+binary; num /= 2; } return binary; } } public class Program { public static void main(String[ ] args) { Scanner sc = new Scanner(System.in); int x = sc.nextInt(); System.out.print(Converter.toBinary(x)); } }
19th Jun 2022, 10:09 PM
Anirudh Trivedi Kondamudi
0
From 'Converter.toBinary(x)', we can tell that this process should be executed from a method toBinary(int) which is from a class or an object called Converter. Converter as a class looks more natural as it is capital and easier to do for this code. That means you have to create a Converter class with one static method String toBinary(int num) and put your implementation in the method. Remember to return binary at the end of the code.
18th May 2021, 2:07 PM
你知道規則,我也是
你知道規則,我也是 - avatar
- 4
Here is my code: def convert(num): if num==1: return "1" else: return (str(int(num) % 2) + str(convert(int(num) // 2))) a=convert(input()) print(a[len(a)::-1])
8th Sep 2021, 3:01 PM
Manuel Carlos Cabanillas
Manuel Carlos Cabanillas - avatar