Home > Net >  Count number of bits set to 1, why non-negative integers?
Count number of bits set to 1, why non-negative integers?

Time:11-24

In Elements of Programming Interviews in Java, the authors say: "Writing a program to count the number of bits that are set to 1 in a nonnegative integer is a good way to get up to speed with primitive types".

Why do they qualify this with 'nonnegative'?

CodePudding user response:

Non-negative means positive or zero.

You are assumed to use shifts and bit operations.

Bit shifts can be sign-extending, which can be misleading. To avoid this issue, you are asked to handle non-negative values only.

But you can handle negative values too, if you want. Java has unsigned shifts >>>.

Sure this is an exercise. In real code you'll use a library implementation. java.lang.Integer has bitCount(int i). I assume bitCount will execute on a hardware as bit-counting instruction, such as x86 popcnt, so it should be better than manual bit manipulation, or at least use a very decent bit manipulation implementation rather than one you'd write as an exercise. There's a whole tag about counting those bits.

CodePudding user response:

Negative integers are stored a little bit differently. In a 4 Bit signed integer, 1111b would be -1, whereas 1000b would be -8, making the count of 1's dependent on the number of bits in the number. That way you can't answer the question anymore.

  • Related