Задача на поиск в массиве количества единиц в двоичном коде - C#
Формулировка задачи:
Нужно чтобы выводилось количество единиц в каждой строке.
Примерно так:
58 -> 111010 -> 4
129 -> 10000001 -> 2
и т.д.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace bit2
{
class Program
{
static void Main(string[] args)
{
int s = 0, i;
const int n = 10;
int[] a = new int[n];
int[] bases = { 2 };
Random rnd = new Random();
for (i = 0; i < n; i++)
a[i] = rnd.Next(0, 255);
Console.WriteLine("Массив:");
foreach (int r in a) Console.WriteLine(r);
for (i = 0; i < n; i++) s += Convert.ToString(a[i], 2).Where(x => x == '1').Count();
Console.WriteLine("Количество единиц = {0}", s);
foreach (int baseValue in bases)
{
Console.WriteLine("\nДля проверки:");
foreach (int r in a)
Console.WriteLine("{0,-15}\t->\t{1}", r, Convert.ToString(r, baseValue));
}
Console.Write("Press any key to continue . . . ");
Console.ReadKey(true);
}
}
}Решение задачи: «Задача на поиск в массиве количества единиц в двоичном коде»
textual
Листинг программы
static void Count(int value, out int ones) {
ones = 0;
while (value != 0) {
if ((value & 1) == 1)
ones++;
value = (value >> 1);
}
}
static void Main(string[] args) {
const int n = 10;
int ones;
Random rnd = new Random();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = rnd.Next(0, 255);
Count(a[i], out ones);
Console.WriteLine("{0} -> {1} -> {2}", a[i], Convert.ToString(a[i], 2), ones);
}
Console.ReadKey();
}