The number of ones

Write a function that takes an unsigned integer (in the form of a binary string) and returns the number of digits ‘1’ in its binary expression (also known as hamming weight).

Tip:

  • Note that in some languages, such as Java, there are no unsigned integer types. 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 the signed integer -3.

Examples can be found on the LeetCode website.

Source: LeetCode link: leetcode-cn.com/problems/nu… Copyright belongs to the Collar buckle network. Commercial reprint please contact official authorization, non-commercial reprint please indicate the source.

Solution 1: traversal

First, use integer.tobinarystring (num) to convert n to a binaryString binaryString;

Then, each character of the string binaryString is iterated to determine if the current character is ‘1’ and if so, result is incremented by 1.

Result is returned as the number of ones in the binary.

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') { result++; }}return result;
    }

    public static void main(String[] args) {
        System.out.println(hammingWeight(20)); }}Copy the code

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