剑指offer_二进制中1的个数
题目描述:输入一个整数,输出二进制中表示的1的个数
如果用Integer.toBinaryString就很容易暴力解决
1 public static int NumberOf1(int n) { 2 int count=0; 3 String str = Integer.toBinaryString(n); 4 System.out.println(str); 5 for (int i = 0; i < str.length(); i++) { 6 if(str.charAt(i)=='1') count++; 7 } 8 return count; 9 }
如果使用bitCount那就更暴力了
1 public int NumberOf1(int n) { 2 return Integer.bitCount(n); 3 }
有一个位运算的技巧
n&(n-1)
这个位运算可以消除掉n 的位级表示中最低的那一位。
n : 10110100 n-1 : 10110011 n&(n-1) : 10110000
运算之后第三位的1没了
时间复杂度:O(M),其中 M 表示 1 的个数。
1 public int NumberOf1(int n) { 2 int cnt = 0; 3 while (n != 0) { 4 cnt++; 5 n &= (n - 1); 6 } 7 return cnt; 8 }

浙公网安备 33010602011771号