There are multiple ways to count number of 1's or set bits in a integer number in Java. You can use bitwise and bit shift operator by your own, or, you can use Java API to count number of set bits. Java 1.5 added two utility method called bitCount(int i) which returns number of 1's in your integer number, java.lang.Long class has similar bitCount(long number) for long primitives. As I have said earlier, Coding questions are important part of any Java interview, and from that recursion and bitwise operations are most popular. Questions like, How to Swap two numbers without temp variable or How to find if a number is positive or negative are some of such questions, which you see now and then in various Java interviews. In this Java tutorial, we will see, How to count number of set bits in a number, for those who don't know what is set bit, it's bit with value 1. For example 2, which is binary 0010 has just one set bit. On the other hand 10, which is 1010 in binary has two set bit or number of one's. In most of cases, Interviewer will ask you to write a Java method without using API. In this article, we will see couple of ways to calculate number of set bit in a number on Java program.
No comments:
Post a Comment