【微软100题】输入一个整数,求该整数的二进制表达中有多少个1

package test;

/**
整数的二进制表示中1的个数
题目:输入一个整数,求该整数的二进制表达中有多少个1。

比如输入10,因为其二进制表示为1010,有两个1。因此输出2。 分析: 方法一:把十进制转换成二进制字符数组。遍历该数组,推断1的个数。 方法二:对于一个int n, n&1的结果就是n转化成二进制数后的最后一位的结果。

考察了位运算 包含微软在内的非常多公司都曾採用过这道题。 * @author Zealot * */ public class MS_28 { private int getNum1(int i) { int reVal = 0; String s =Integer.toBinaryString(i); char[] chars = s.toCharArray(); for(char c: chars) { if(c=='1'){ reVal++; } } return reVal; } private int getNum2(int i1) { int count=0; while(i1!=0) { if((i1&1)==1) { count++; } i1 = i1>>1; } return count; } public static void main(String[] args) { MS_28 ms28 = new MS_28(); System.out.println(ms28.getNum2(10)); } }


原文地址:https://www.cnblogs.com/yfceshi/p/7354011.html