Untitled

mail@pastecode.io avatar
unknown
java
2 years ago
1.3 kB
4
Indexable
Never
import java.util.Scanner;

public class Binary
{
  public static void main(String[] args)
  {
    Scanner keyboard = new Scanner(System.in);

    System.out.print("Enter a whole decimal number: ");
    
    int decimalNumber = keyboard.nextInt();
    String decimalConverted = convertBinary(decimalNumber);
    
    System.out.printf("%d in binary is %s", decimalNumber, decimalConverted);
  }

  /*
   *
   * 
   */
  public static String convertBinary(int decimalInput)
  {
    String binaryConversion = "";
    int remainder = 0;
    while(decimalInput > 0)
    {
      remainder = decimalInput % 2;
      decimalInput /= 2;
      binaryConversion = binaryConversion.concat(Integer.toString(remainder));
    }
    return reverseBinary(binaryConversion);
  }

  /*
   *
   * 
   */
  public static String reverseBinary(String unreversedBinary)
  {
    String binaryConversionReversed = "";
    for(int i = 0; i < unreversedBinary.length(); i++)
    {
      char placeHolder = unreversedBinary.charAt(i);
      int last = unreversedBinary.length() - 1;
      binaryConversionReversed = binaryConversionReversed.replace(placeHolder, binaryConversionReversed.charAt(last));
    }
    return binaryConversionReversed;
  }
}