Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created July 6, 2016 17:24
Show Gist options
  • Save jianminchen/d2f6022094fcdb41fb7e7cae8b30c725 to your computer and use it in GitHub Desktop.
Save jianminchen/d2f6022094fcdb41fb7e7cae8b30c725 to your computer and use it in GitHub Desktop.
Number 1 bits
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace number1bits_fCodeLab
{
class Program
{
/*
* Write a function that takes an unsigned integer and returns the number of 1 bits it has.
Example:
The 32-bit integer 11 has binary representation
00000000000000000000000000001011
so the function should return 3.
Note that since Java does not have unsigned int, use long for Java
*/
static void Main(string[] args)
{
}
public class Solution
{
public int numSetBits(long a)
{
int count = 0;
while (a > 0)
{
long leastSignificantBit = a & 1;
if (leastSignificantBit == 1)
count++;
a = a >> 1; // bug001 - writing, forget "a =" in first writing, need compiler's help
}
return count;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment