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:
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.
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework