Leetcode-191-number of bit 1


Number of bits 1

Title Description: write a function. The input is an unsigned integer (in the form of binary string) and returns the number of digits with ‘1’ in its binary expression (also known as Hamming weight).


  • Note that in some languages, such as Java, there is no unsigned integer type. In this case, both input and output will be specified as signed integer types and should not affect your implementation, because the internal binary representation of an integer is the same whether it is signed or unsigned.
  • In Java, the compiler uses binary complement notation to represent signed integers. Therefore, in example 3 above, the input represents a signed integer – 3.

See leetcode’s official website for an example.

Source: leetcode
Link: https://leetcode-cn.com/probl…
The copyright belongs to Lingkou network. For commercial reprint, please contact the official authorization, and for non-commercial reprint, please indicate the source.

Solution 1: traversal

First, useInteger.toBinaryString(num)Method converts n to binary string binarystring;

Then, traverse each character of the string binarystring to determine whether the current character is’ 1 ‘. If so, add 1 to the result;

Finally, the returned result is the number of 1 in binary bits.

public class LeetCode_191 {
    public static int hammingWeight(int n) {
        String binaryString = Integer.toBinaryString(n);
        int result = 0;
        for (char c : binaryString.toCharArray()) {
            if (c == '1') {
        return result;

    public static void main(String[] args) {

[daily message]Life is like rain, please hold an umbrella and forgive me! When the rain is over, it will return you a blue sky and give you a rainbow.

Recommended Today

On the mutation mechanism of Clickhouse (with source code analysis)

Recently studied a bit of CH code.I found an interesting word, mutation.The word Google has the meaning of mutation, but more relevant articles translate this as “revision”. The previous article analyzed background_ pool_ Size parameter.This parameter is related to the background asynchronous worker pool merge.The asynchronous merge and mutation work in Clickhouse kernel is completed […]