PRASHNIKAप्रश्निका
Back to the paper

An Evil Number is a number which contains even number of 1’s in its binary equivalent. Example…

Computer Science202410 marksProgram
An Evil Number is a number which contains even number of 1’s in its binary equivalent. Example: Binary equivalent of 10 = 1010 which contains even number on 1’s. Thus, 10 is an Evil Number. Design a class Evil to check if a given number is an Evil number or not. Some of the members of the class are given below: Class name : Evil Data members/instance variables: num : to store a positive integer number bin : to store the binary equivalent Methods / Member functions: Evil( ) : default constructor to initialize the data member with legal initial value void acceptNum( ) : to accept a positive integer number void rec_bin (int x) : to convert the decimal number into its binary equivalent using recursive technique void check( ) : to check whether the given number is an Evil number by invoking the function rec_bin() and to display the result with an appropriate message Specify the class Evil giving details of the constructor( ), void acceptNum( ), void rec_bin(int) and void check( ). Define a main( ) function to create an object and call all the functions accordingly to enable the task.

Answer

Answer

AI
import java.util.Scanner;

class Evil
{
    int num;
    String bin;

    Evil()
    {
        num = 0;
        bin = "";
    }

    void acceptNum()
    {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a positive integer: ");
        num = sc.nextInt();
    }

    void rec_bin(int x)
    {
        if (x > 0)
        {
            rec_bin(x / 2);
            bin = bin + (x % 2);
        }
    }

    void check()
    {
        rec_bin(num);
        int count = 0;
        for (int i = 0; i < bin.length(); i++)
        {
            if (bin.charAt(i) == '1')
                count++;
        }
        if (count % 2 == 0)
            System.out.println(num + " is an Evil Number.");
        else
            System.out.println(num + " is not an Evil Number.");
    }

    public static void main(String args[])
    {
        Evil obj = new Evil();
        obj.acceptNum();
        obj.check();
    }
}
Explanation: rec_bin(x) recursively divides x by 2, and after the recursive call returns (i.e. once x becomes 0), it appends each remainder (x%2) to the string `bin` on the way back up the call stack, which builds the binary equivalent in the correct (MSB to LSB) order. check() calls rec_bin(num), counts the number of '1' characters in `bin`, and reports the number as Evil if that count is even. Tested (run for real): for num=10, rec_bin builds bin="1010" (two 1's, even), and the program correctly printed "10 is an Evil Number."
Objects

From ISC 2024 Specimen Computer Science Paper 1, question 6.