COUNT 1s in BINARY FORMAT OF A NUMBER
namespace Count1_sInANum
{
class Program
{
public static int NumberOf1s(int Num)
{
int count = 0;
if (Num > 0)
{
count = 0;
while (Num > 0)
{
count++;
Num = Num &(Num - 1);
}
}
else if (Num == 0) count = 0;
else if (Num < 0)
{
Num = ~Num;
count = 8 * sizeof(int);
while (Num > 0)
{
count--;
Num = Num & (Num - 1);
}
}
return count;
}
static void Main(string[] args)
{
Console.WriteLine(NumberOf1s(-5));
}
}
}
No comments:
Post a Comment