Problem Statement / Task: You are given a number and your task is to find whether the given number is an odious number or not.
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.
Here is the simple approach you can follow to solve this problem.
Prerequisite:
lenght()
, charAt()
.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"); } }
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.