天天看点

【剑指offer】 面试题10: 二进制中1的个数

题目描述:

输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。

九度 : http://ac.jobdu.com/problem.php?pid=1513

package com.offer.chapter_2;

import java.util.Scanner;

public class Interviews_10 {
	
	public static int countOne(int num) {
		int count = 0;
		while(num != 0) {
			count ++;
			num = (num-1) & num;
		}
		return count;
	}
	
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		
	
			int num = scanner.nextInt();
			while(num -- > 0) {
				int a = scanner.nextInt();
				System.out.println(countOne(a));
			}
			
	}
}