Answers for "binary program in java"

1

Java program to convert decimal number to binary & count number of 1s

// decimal to binary conversion in java
import java.util.Scanner;
public class DecimalBinaryDemo
{
   public static void main(String[] args)
   {
      int number, count = 0, temp;
      String strConvert = "";
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter a decimal number : ");
      number = sc.nextInt();
      // decimal to binary java
      while(number > 0)
      {
         temp = number % 2;
         if(temp == 1)
         {
            count++;
         }
         strConvert = strConvert + " " + temp;
         number = number / 2;
      }
      System.out.println("Decimal to binary in java : " + strConvert);
      System.out.println("Number of 1s : " + count);
      sc.close();
   }
}
Posted by: Guest on November-02-2020
0

binary code code java

class DecimalBinaryExample{
 
  public void convertBinary(int num){
     int binary[] = new int[40];
     int index = 0;
     while(num > 0){
       binary[index++] = num%2;
       num = num/2;
     }
     for(int i = index-1;i >= 0;i--){
       System.out.print(binary[i]);
     }
  }
 
  public static void main(String a[]){
     DecimalBinaryExample obj = new DecimalBinaryExample();
     System.out.println("Binary representation of 124: ");
     obj.convertBinary(124);
     System.out.println("\nBinary representation of 45: ");
     obj.convertBinary(45);
     System.out.println("\nBinary representation of 999: ");
     obj.convertBinary(999);
  }
}
Posted by: Guest on January-01-2021

Code answers related to "binary program in java"

Code answers related to "Java"

Java Answers by Framework

Browse Popular Code Answers by Language