题解 | #求int型正整数在内存中存储时1的个数#
求int型正整数在内存中存储时1的个数
http://www.nowcoder.com/practice/440f16e490a0404786865e99c6ad91c9
方法一
import java.io.*; import java.util.*; public class Main{ public static void main(String[] args) throws Exception{ Scanner sc = new Scanner(System.in); while(sc.hasNextInt()){ int n = sc.nextInt(); System.out.println(Integer.bitCount(n)); } } }
方法二
import java.io.*; import java.util.*; public class Main{ public static void main(String[] args) throws Exception{ Scanner sc = new Scanner(System.in); while(sc.hasNextInt()){ int n = sc.nextInt(); int count = 0; while(n != 0){ if((n&1) == 1){ count++; } n >>>= 1; } System.out.println(count); } } }