
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Evil Number with Example in C++
In this problem, we are given an array a number N. Our task is to check whether the number is an evil Number or Odious Number.
Evil Number: It is a positive number which has an even number of 1’s in its binary expansion.
Example: 5, 17
Odious Number: It is a positive number which has an odd number of 1’s in its binary expansion.
example : 4, 6
Let’s take an example to understand the problem,
Input: N = 65
Output: Evil Number
Explanation:
Binary Expansion of 65 : 1000001
Solution Approach:
A simple solution to the problem is by finding the binary expansion of the number and then counting the number of 1’s in the expansion. If the count is even the number is an evil number otherwise it is an Odious number.
Program to illustrate the working of our solution,
Example
#include <iostream> using namespace std; int isEvilNumber(int n) { int count = 0; while (n != 0) { int r = n % 2; if(r == 1) count++; n = n / 2; } if (count % 2 == 0) return 1; else return 0; } int main(void) { int num = 2049; if (isEvilNumber(num) ) cout<<"The number "<<num<<" is an Evil Number"; else cout<<"The number "<<num<<" is an Odious Number"; return 0; }
Output −
The number 2049 is an Evil Number
Advertisements