美文网首页
LeetCode191. Number of 1 Bits

LeetCode191. Number of 1 Bits

作者: Yuu_CX | 来源:发表于2016-11-15 09:56 被阅读0次

Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight).For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, so the function should return 3.
计算出二进制数中所含‘1’的个数:
C++

class Solution {  
public:  
    int hammingWeight(uint32_t n) {  
        int count = 0;  
        uint32_t ss = n;  
        while(ss!=0){  
            if(ss%2){  
                count++;  
            }  
            ss /= 2;  
        }  
        return count;  
    }  
};

java

import java.util.*;
public class Main{
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int num = in.nextInt();   
        int count = 0;
        while(num!=0){  
            if(num%2==1){  
                count++;  
            }  
            num /= 2;  
        }  
        System.out.println(count);
    }
}
import java.util.Scanner;

public class Main {

    private static Scanner scanner;

    public static void main(String[] args) {
        scanner = new Scanner(System.in);
        
        int number = findNumberOf1(scanner.nextInt());
        System.out.println(number);

    }

    public static int findNumberOf1(int num) {
        
        int count = Integer.bitCount(num);
        
        return count;
    }
}

相关文章

网友评论

      本文标题: LeetCode191. Number of 1 Bits

      本文链接:https://www.haomeiwen.com/subject/ijvkpttx.html