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


相关文章:

  • 2021-11-15
  • 2022-03-15
  • 2021-04-19
  • 2021-07-23
  • 2021-07-15
猜你喜欢
  • 2021-06-21
  • 2022-12-23
  • 2022-12-23
  • 2021-12-04
  • 2021-12-11
  • 2022-03-15
  • 2022-12-23
相关资源
相似解决方案