【华为机试】—— 15.求int型正整数在内存中存储时1的个数

题目

 

解法

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));
    }

}

 

posted @ 2018-07-03 16:43  befmain  阅读(283)  评论(0)    收藏  举报