0

I am trying to convert a decimal number to binary but the code I've written doesn't work in all test cases. Here's the code:

import java.util.Scanner;

public class Converter{
    public static int toBinary(int num) {
        String binary="";
        while (num>0){
            binary = (num%2)+binary;
            num /=2;
        }
        int bin = Integer.parseInt(binary);
        return bin;
    }
}

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));
    }
}

I would be grateful if somebody could tell me what's wrong.

Noa
  • 11
  • 1
  • *doesn't work* is not an error description. Please explain what it means – Jens Oct 16 '22 at 14:41
  • `System.out.println(Integer.toBinaryString(x) + " or " + Integer.toString(x, 2));` – Elliott Frisch Oct 16 '22 at 14:42
  • What you're doing doesn't actually make sense. You give your method an ```int``` and return an ```int``` . ```int``` doesn't have a format (binary, decimal, octal etc.) - that's a string thing. You should be returning a ```String``` – g00se Oct 16 '22 at 14:51
  • Does this answer your question? [Converting Decimal to Binary Java](https://stackoverflow.com/questions/14784630/converting-decimal-to-binary-java) – odaiwa Oct 16 '22 at 15:14
  • ...and actually you're producing a *different* number. Entering 8 will give you 1000 (one thousand, not binary 8) – g00se Oct 16 '22 at 15:22
  • Converting decimal to binary doesn't convert an int to an int. It converts a string to a string. – Louis Wasserman Oct 16 '22 at 15:47
  • If your toBinary routine is to work as you expect, you can just collapnse it to `int toBinary(int num) { return num; }` --- because all you're attempting to do (and getting it wrong) is to split a number into digits, here base 2, and then combining those digits into a number. – access violation Oct 16 '22 at 22:55

0 Answers0