Number of 1s in 2's complement representation
Source: Interview Street CodeSprint (slightly modified) Problem: One of the basics of Computer Science is knowing how numbers are represented in 2's complement. Imagine that you write down all numbers between A and B inclusive in 2's complement representation using 32 bits. How many 1's will you write down in all ? Input: Two integers A and B Output: The number of 1s Constraints: -2^31 <= A <= B <= 2^31 - 1 Find the asymptotically optimal algorithm. Solution: Highlight the part between the * symbols for the answer. * Optimal algorithm: O(number of bits) - i.e. O(32), constant per query - using digit DP. Split the answer: countOnes(A, B) = F(B) - F(A - 1), where F(X) = total 1-bits in the 32-bit two's complement representations of all numbers from -2^31 to X (or 0 to X for X >= 0). For X >= 0 (plain binary): group numbers by their most significant bit. Group m has 2^m numbers, each contributing one m-th bit plus all the bits of the pre...