Program to Check Odious Number in Java, Python, C/++

Program to Check Odious Number in Java, Python, C/++

Problem Statement / Task: You are given a number and your task is to find whether the given number is an odious number or not.

What is Odious Number?

An odious number is a non-negative number that has an odd number of 1’s in its binary representation.

For example: Suppose you have a number 7. Its binary representation is 111. Since it has three 1’s hence it is an odious number.

Algorithm and Approach

Here is the simple approach you can follow to solve this problem.

  1. Convert the given number into its binary form.
  2. Count the frequency of 1’s in it.
  3. Check for odd or even frequency.
  4. Display the result

Program to Check Odious Number

Java Program

Prerequisite:

Code:

import java.util.*;
public class Odious {
    public static void main(String[] args) {
        // User Input
        Scanner sc = new Scanner(System.in);
        int input = sc.nextInt();

        // Binary of given input
        String binaryOfInput = Integer.toBinaryString(input);
        System.out.println(binaryOfInput);
        int count = 0;

        // count the frequency of 1's
        for (int i = 0;i < binaryOfInput.length();i++) {
            if (binaryOfInput.charAt(i) == '1')
                count ++;
        }

        // check whether count is even or not.
        if (count % 2 != 0)
            System.out.println("Number is odious");
        else
            System.out.println("Number is not Odious");
    }
}

Python Program

Prerequisite:

If you get the prerequisite and algorithm, below code is self explanatory.

Code:

num = int(input('Enter the number: '))
binary_num = bin(num).replace("0b", "") 
if binary_num.count('1') % 3 :
    print("Number is not Odious.")
else:
    print("Number is Odious.")

Here, we are converting an integer to a binary string using the inbuilt method bin(). The converted binary string will be having 0b as prefix to represent it as a binary string. Remove it using the string method replace().

Output:

Enter the number: 7
Number Odious.
Enter the number: 10
Number is not Odious.

Check more coding examples for practicing asked in coding interviews.

Note: You can implement a program to check odious number in Python, C/C++ or any other language. For a full video explanation of this program click here.

Leave a Reply

Your email address will not be published. Required fields are marked *