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

  • برمجة سي شارب
  • برمجة

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

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

الأجوبة

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;
        }
    }
}
هل كان المحتوى مفيد؟

تبحث عن مدرس اونلاين؟

محتاج مساعدة باختيار المدرس الافضل؟ تواصل مع فريقنا الان لمساعدتك بتأمين افضل مدرس
ماهو التخصص الذي تبحث عنه؟
اكتب هنا...