Skip to content

Instantly share code, notes, and snippets.

@N02870941
Last active September 12, 2018 09:16
Show Gist options
  • Save N02870941/ee8d1eb27a0578f16dab452afa73556c to your computer and use it in GitHub Desktop.
Save N02870941/ee8d1eb27a0578f16dab452afa73556c to your computer and use it in GitHub Desktop.
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