Dado un número decimal como entrada, necesitamos escribir un programa para convertir el número decimal dado en un número binario equivalente.
Ejemplos:
Java
// Java program to convert a decimal // number to binary number import java.io.*; class GFG { // function to convert decimal to binary static void decToBinary(int n) { // array to store binary number int[] binaryNum = new int[1000]; // counter for binary array int i = 0; while (n > 0) { // storing remainder in binary array binaryNum[i] = n % 2; n = n / 2; i++; } // printing binary array in reverse order for (int j = i - 1; j >= 0; j--) System.out.print(binaryNum[j]); } // driver program public static void main (String[] args) { int n = 17; System.out.println("Decimal - " + n); System.out.print("Binary - "); decToBinary(n); } } // Contributed by Pramod Kumar
Java
// Java program to Decimal to binary conversion // using bitwise operator // Size of an integer is assumed to be 32 bits class gfg { // Function that convert Decimal to binary public void decToBinary(int n) { // Size of an integer is assumed to be 32 bits for (int i = 31; i >= 0; i--) { int k = n >> i; if ((k & 1) > 0) System.out.print("1"); else System.out.print("0"); } } } class geek { // driver code public static void main(String[] args) { gfg g = new gfg(); int n = 32; System.out.println("Decimal - " + n); System.out.print("Binary - "); g.decToBinary(n); } } // This code is contributed by mits
Java
// Java implementation of the approach import java.io.*; class GFG { // Function to return the binary // equivalent of decimal value N static int decimalToBinary(int N) { // To store the binary number int B_Number = 0; int cnt = 0; while (N != 0) { int rem = N % 2; double c = Math.pow(10, cnt); B_Number += rem * c; N /= 2; // Count used to store exponent value cnt++; } return B_Number; } // Driver code public static void main(String[] args) { int N = 17; System.out.println("Decimal - " + N); System.out.print("Binary - "); System.out.println(decimalToBinary(N)); } } // This code is contributed by ajit.
Publicación traducida automáticamente
Artículo escrito por GeeksforGeeks-1 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA