javabit-manipulationbit-shiftbitmaskhardcode

How this code block avoiding hard-coding. Elements Of Programming Interviews Question 5.1


I recently started preparing for job interviews and came across with this example question which ask us to find how many bits are set to 1 in a number and answer code block.

The Following program tests bits one at a time starting with the least significant bit. It illustrates shifting and masking; it also shows how to avoid hard-coding the size of the integer word

public static short countBits(int x){

        short numBits = 0;
        while (x != 0){
            numBits += (x & 1);
            x = x >>> 1;
        }
        return numBits;
    }

What I do not understand here is how this code avoiding hard-coding. The wikipedia article says about hard coding;

Hard coding is the software development practice of embedding data directly into the source code of a program or other executable object, as opposed to obtaining the data from external sources or generating it at runtime.

In this article it says we are hard-coding if we are taking data directly from source code. Which is exactly what we are doing in the method. We are taking the data from source code:

Parameter → int x is hard coded.

The second part I do not understand is how we are not hard coded size of the integer word. What is that mean?


Solution

  • You are not doing x&1+(x>>>1)&1+(x>>>2)&1+...(x>>>63)&1 or for(int i=0; i<64; i++) { ... }. These both would assume that integers have 64 bits (which btw would take unnecessarily more time as integers only use 32 bits in java, but that's the reason you want to avoid hard-coding). Your method doesn't care how many bits an integer has, it just cares that there are still 1's somewhere in it.