题解 | #二进制中1的个数#
二进制中1的个数
http://www.nowcoder.com/practice/8ee967e43c2c4ec193b040ea7fbb10b8
知识点一:
无符号右移运算符 >>>无符号右移运算符是补上0
右移运算符 >> 右移时左边是补上符号位,负数会补上1
一开始的思路是:
例如:
(101 & 1) ^ 1
(101 & 10) ^ 10
以上这种思路不适合于负数,如-1:111111...1111
最后思路:
例如,利用无符号左移动,这样就解决了负数的问题
(101 & 1)
( 10 & 1)
( 1 & 1)
还有一种思路利用 (x & x - 1) 结合无符号做移动
(1011 & 1010) > 0
(101 & 100) > 0
(10 & 1) > 0
public class Solution { public int NumberOf1(int n) { int count = 0; int target = n; while(target != 0) { if ((target & 1) > 0) { count++; } target = target >>> 1; } return count; } }