Your browser does not seem to support JavaScript. As a result, your viewing experience will be diminished, and you have been placed in read-only mode.

Please download a browser that supports JavaScript, or enable it if it's disabled (i.e. NoScript).

vector<int> countBits(int num) { vector<int> bits(num+1, 0); for (int i = 1; i <= num; i++) bits[i] += bits[i & (i-1)] + 1; return bits; }

awesome solution from Dean God

Jesus. This is sooooo AWESOME!!

Thank you. :)

"bits[i] += " can be changed to "bits[i] ="

It method took me several minutes to figure out the logic here.

i -> i & i -1 modify the right-to-left first-met 1 to 0, thus reducing the number of ones by 1

i -> i & i -1

X..X 1 0..0 -> X..X 0 0..0, where X means 0 or 1, X..X means any numbers of X (including zero X )

X..X 1 0..0 -> X..X 0 0..0

freaking awesome!

how to discover this regularities?

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.