求int型正整数在内存中存储时1的个数
求int型正整数在内存中存储时1的个数
http://www.nowcoder.com/questionTerminal/440f16e490a0404786865e99c6ad91c9
方法1:
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int res=0; int x=sc.nextInt(); while (x!=0){ if ((x&1)==1){ res++; } x=x>>1; } System.out.println(res); } }
方法2:
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int res=0; int x=sc.nextInt(); String s=Integer.toBinaryString(x); for (int i=0;i<s.length();i++){ if (s.charAt(i)=='1'){ res++; } } System.out.println(res); } }