[The offer to prove safety] of the binary number 1

The number of binary 1

topic

A 32-bit integer inputs, the output of the binary number represents the number 1.

note:

  • Complement negative number whose absolute value is represented in the computer by.

Sample 1

Input: 9
Output: 2
Explanation: 9 representation is binary 1001, a total of 2 1.

Sample 2

Input: -2
Output: 31
Explanation: 2 in the computer is represented as 11111111111111111111111111111110
a total of 31 1.

answer

Since the upper right negative automatically fill 1, so if a negative signed right shift operation directly, an error occurs TLE

So here we need to be converted to a signed number cast to unsigned

class Solution {
public:
    int NumberOf1(int n) {
        int sum = 0;
        unsigned int un = n;
        while (un) {
            if (un & 1) sum ++;
            un >>= 1;
        }
        return sum;
    }
};
Published 10 original articles · won praise 0 · Views 559

Guess you like

Origin blog.csdn.net/weixin_44922845/article/details/104107365