Last active
September 12, 2018 09:16
-
-
Save N02870941/ee8d1eb27a0578f16dab452afa73556c to your computer and use it in GitHub Desktop.
Convert decimal integer to binary string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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