首页 > 技术文章 > 【华为机试】—— 15.求int型正整数在内存中存储时1的个数

befmain 2018-07-03 16:43 原文

题目

 

解法

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        int num = sc.nextInt();
        int res = 0;
        while(num !=0 ){
            if( (num&1) == 1){
                res++;
            }
            //无符号右移
            num >>>= 1;
        }
        System.out.println(res);
    }

}

 

解法2

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        
        Scanner scanner = new Scanner(System.in);
        
        int x = scanner.nextInt();
        
        System.out.println(Integer.bitCount(x));
    }

}

 

推荐阅读