How to Count number of 1s (Set Bits) in Given Bit Sequence in Java

Good morning folks, In today's article, we are going to discuss one of the frequently asked bit manipulation based interview question, how do you count the number of set bits in given bit sequence? It is also asked as how to count the number of 1s in given number? Both are the same question because 1 is also known as set bit.  For example if given input is 1000110010 than your program should return 4, as three are only four set bits in this bit sequence. There are many techniques to solve this problem. Best way to learn why a given algorithm works is to take a pencil and run though a few examples. The solution presented in this article, you might have seen this already in hackers delight, runs through a loop and clears the lowest set bit of number during each iteration. When no set bit is left (i.e. number==0) than the number of iterations is returned. That's your number of 1s or set bits in given bit sequence. Let's learn more about how this algorithm works.
Read more »