Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,894 questions

51,825 answers

573 users

How to check if a number is evil number (binary representation contains even number of 1) in C#

1 Answer

0 votes
// Evil number = positive whole number whose binary representation contains an even number of 1's

using System;

public class Program
{
	public static int countNumberOfOne(string binaryNumber) {
		int length = binaryNumber.Length;

		int count = 0;
		char ch;

		for (int i = 0; i < length; i++) {
			ch = binaryNumber[i];
			if (ch == '1') {
				count++;
			}
		}

		return count;
	}

	public static bool checkEvilNumber(int number) {
		string binaryNumber = Convert.ToString(number, 2);

		Console.Write(number + " = " + binaryNumber + " = ");

		return (countNumberOfOne(binaryNumber) % 2 == 0) ? true : false;
	}

	public static void Main(string[] args)
	{
		int number = 23;
		Console.WriteLine(checkEvilNumber(number));

		number = 9863;
		Console.WriteLine(checkEvilNumber(number));
	}
}




/*
run:
   
23 = 10111 = True
9863 = 10011010000111 = False
  
*/

 



answered Nov 25, 2023 by avibootz
edited Nov 25, 2023 by avibootz
...