Created
January 20, 2021 10:15
-
-
Save monir-zaman/764a408fbfb748d0e07cba6a6d33f99f to your computer and use it in GitHub Desktop.
This file contains hidden or 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
import java.util.Scanner; | |
public class DecimalToBinary { | |
public static void main(String[] args) | |
{ | |
Scanner scanner = new Scanner(System.in); | |
//int decimalNumber = 1024; // output is 10000000000 | |
int decimalNumber = scanner.nextInt(); | |
System.out.println(convertDecToBinTypically(decimalNumber)); | |
System.out.println(convertDecToBinWithRecursion(decimalNumber)); | |
} | |
private static String convertDecToBinWithRecursion(int decimalNumber) { | |
if (decimalNumber == 0) return "0"; | |
else if (decimalNumber == 1) return "1"; | |
return convertDecToBinWithRecursion(decimalNumber/2) + decimalNumber%2; | |
} | |
private static String convertDecToBinTypically(int decimalNumber) { | |
String convertedToBinary = ""; | |
while (decimalNumber != 0) { | |
if (decimalNumber%2 ==1) convertedToBinary = "1"+convertedToBinary; | |
else convertedToBinary = "0"+convertedToBinary; | |
decimalNumber /= 2; | |
} | |
return convertedToBinary == "" ? "0" : convertedToBinary; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment