Decimal to Binary conversion (using array)


Conversion of decimal to binary using array

import java.io.*;
import java.util.*;

class binaryArray
{
// 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)
{ Scanner sc=new Scanner(System.in);
int n ;
System.out.println("Enter a decimal value:");
n=sc.nextInt();
decToBinary(n);
}
}

Output:

Enter a decimal value:
7
111

Evil Number/Odious Number in java


An evil number is a non-negative number that has an even number of 1s in its binary expansion. (Binary Expansion – is representation of a number in the binary numeral system or base-2 numeral system which represents numeric values using two different symbols: typically 0 (zero) and 1 (one)).

Odious Numbers: Numbers that are not Evil are called Odious Numbers. Given a number, the task is to check if it is Evil Number or Odious Numbers.

import java.util.*;
class EvilNumber 
{
  String toBinary(int n) // Function to convert a number to Binary
  {
   int r;
   String s=""; //variable for storing the result
   char dig[]={'0','1'}; //array storing the digits (as characters) in a binary number system
   while(n>0)
   {
       r=n%2; //finding remainder by dividing the number by 2
       s=dig[r]+s; //adding the remainder to the result and reversing at the same time
       n=n/2;
    }
    return s;
  }


  int countOne(String s) // Function to count no of 1’s in binary number
  {   
      int c = 0, l = s.length();
      char ch;
      for(int i=0; i<l; i++)
      {
          ch=s.charAt(i);
          if(ch=='1')
          {
              c++;
          }

      }
      return c;
  }
  public static void main(String args[])
  {
      EvilNumber ob = new EvilNumber();
      Scanner sc = new Scanner(System.in);
      System.out.print("Enter a positive number : ");
      int n = sc.nextInt();
      String bin = ob.toBinary(n);
      System.out.println("Binary Equivalent = "+bin);
      int x = ob.countOne(bin);
      System.out.println("Number of Ones = "+x);
      if(x%2==0)
        System.out.println(n+" is an Evil Number.");
      else
        System.out.println(n+" is  an Odious Number.");
  }
}

Output:

Enter a positive number : 23
Binary Equivalent = 10111
Number of Ones = 4
23 is an Evil Number.


Enter a positive number : 21
Binary Equivalent = 10101
Number of Ones = 3
21 is an Odious Number.