Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

C# Sharp Exercises: Count number of ones and zeros in the binary representation of a given integer

C# Sharp Basic: Exercise-90 with Solution

Write a C# Sharp program to count number of ones and zeros in the binary representation of a given integer.

Sample Solution:

C# Sharp Code:

using System;
using System.Linq;
namespace exercises
{
    class Program
    {
        static void Main(string[] args)
        {
            int n = 12; 
            Console.WriteLine("Original number: " +n);
            Console.WriteLine("Number of ones and zeros in the binary representation of the said number:");
            Console.WriteLine(test(n));
            n = 1234;
            Console.WriteLine("\nOriginal number: " + n);
            Console.WriteLine("Number of ones and zeros in the binary representation of the said number:");
            Console.WriteLine(test(n));
        }
        public static string test(int n)
        {
            int ones =  Convert.ToString(n, 2).Count(c => c == '1');
            int zeros = Convert.ToString(n, 2).Count(c => c == '0');

            return "Number of ones: " + ones + "\nNumber of zeros: " + zeros;
        }
    }
}

Sample Output:

Original number: 12
Number of ones and zeros in the binary representation of the said number:
Number of ones: 2
Number of zeros: 2

Original number: 1234
Number of ones and zeros in the binary representation of the said number:
Number of ones: 5
Number of zeros: 6

Flowchart:

Flowchart: C# Sharp Exercises - Count number of ones and zeros in the binary representation of a given integer.

C# Sharp Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a C# Sharp program to count positive and negative numbers in a given array of integers.
Next: Write a C# Sharp program to remove all the values except integer values from a given array of mixed values.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.