Skip to content

Instantly share code, notes, and snippets.

@N02870941 N02870941/ToBinary.java
Last active Sep 12, 2018

Embed
What would you like to do?
Convert decimal integer to binary string
public class ToBinary {
/**
* Converts a positive integer to binary.
*
* @param decimal Decimal number.
* @return Binary string.
*/
public static String binary(int decimal) {
// See - https://www.youtube.com/watch?v=XdZqk8BXPwg
if (decimal <= 0)
return String.valueOf(decimal);
String next;
StringBuilder builder;
builder = new StringBuilder();
while (decimal >= 1) {
next = decimal % 2 == 0 ? "0" : "1";
builder.insert(0, next);
decimal /= 2;
}
return builder.toString();
}
//------------------------------------------------------------------------------
public static void main(String[] args) {
System.out.println(binary(Integer.parseInt(args[0])));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.