Number of bits 1

1. Demand

  • Write a function, the input is an unsigned integer (in the form of a binary string), and return the number of digits in the binary expression whose digits are '1'.

Example 1:

Input: 00000000000000000000000000001011
Output: 3
Explanation: In the input binary string 00000000000000000000000000001011, a total of three bits are '1'.

Two, bit operation

2.1 Thinking analysis

  1. The idea of ​​this question is to reverse the binary digits : https://blog.csdn.net/Sruggle/article/details/113888614 A link in the idea of ​​counting the number of occurrences of 1 from low to high;

2.2 Code implementation

public class Solution {
    // you need to treat n as an unsigned value
    public int hammingWeight(int n) {
        int res = 0;
        for(int i = 0; i < 32; i++) {
            if((n & 1) == 1) {
                res++;
            }
            n = n >> 1;
        }
        return res;
    }
}

2.3 Complexity analysis

  • The time complexity is O(1);
  • The space complexity is O(1);

Guess you like

Origin blog.csdn.net/Sruggle/article/details/113891400