# 第1天 位运算-二进制中1的个数

>>(右移)

<<(左移)

&

`/** *  面试题10 *   *  2014-1-15 */public class NumberOfInBinary {/** * 每次向右移动一位， * 如果是负数右移左侧补1， * 会陷入死循环 *  * @param n 可以是负整数、0、正整数 * @return  */int numberOf(int n) {int count = 0;while (n != 0) {if ((n & 1) == 1) {count++;}n >>= 1;}return count;}/** * 解决负数会死循环的BUG * 每次向左移，右侧总是补0 *  * @param n * @return */int numberOf1(int n) {int count = 0;int flag = 1;while (flag != 0) {if ( (n & flag) != 0) {count++;}flag <<= 1;}return count;}/** *  * n与n-1 相与 得到的值二进制刚好是n的值去掉1个1 *  * @param n * @return */int numberOf2(int n) {int count = 0;while (n != 0) {count++;n = (n - 1) & n;}return count;}public static void main(String[] args) {boolean flag = true;NumberOfInBinary numberOfInBinary = new NumberOfInBinary();flag &= numberOfInBinary.numberOf(10) == 2;flag &= numberOfInBinary.numberOf(9) == 2;flag &= numberOfInBinary.numberOf(8) == 1;flag &= numberOfInBinary.numberOf(7) == 3;flag &= numberOfInBinary.numberOf(6) == 2;flag &= numberOfInBinary.numberOf(5) == 2;flag &= numberOfInBinary.numberOf(4) == 1;flag &= numberOfInBinary.numberOf(3) == 2;flag &= numberOfInBinary.numberOf(2) == 1;flag &= numberOfInBinary.numberOf(1) == 1;flag &= numberOfInBinary.numberOf(0) == 0;//flag &= numberOfInBinary.numberOf(-1) == 32;  // 负数会陷入死循环flag &= numberOfInBinary.numberOf1(5) == 2;flag &= numberOfInBinary.numberOf1(4) == 1;flag &= numberOfInBinary.numberOf1(3) == 2;flag &= numberOfInBinary.numberOf1(2) == 1;flag &= numberOfInBinary.numberOf1(1) == 1;flag &= numberOfInBinary.numberOf1(0) == 0;flag &= numberOfInBinary.numberOf1(-1) == 32;flag &= numberOfInBinary.numberOf1(-2) == 31;flag &= numberOfInBinary.numberOf1(-3) == 31;flag &= numberOfInBinary.numberOf1(-4) == 30;flag &= numberOfInBinary.numberOf1(-5) == 31;flag &= numberOfInBinary.numberOf2(10) == 2;flag &= numberOfInBinary.numberOf2(9) == 2;flag &= numberOfInBinary.numberOf2(8) == 1;flag &= numberOfInBinary.numberOf2(7) == 3;flag &= numberOfInBinary.numberOf2(6) == 2;flag &= numberOfInBinary.numberOf2(5) == 2;flag &= numberOfInBinary.numberOf2(4) == 1;flag &= numberOfInBinary.numberOf2(3) == 2;flag &= numberOfInBinary.numberOf2(2) == 1;flag &= numberOfInBinary.numberOf2(1) == 1;flag &= numberOfInBinary.numberOf2(0) == 0;flag &= numberOfInBinary.numberOf2(-1) == 32;flag &= numberOfInBinary.numberOf2(-2) == 31;flag &= numberOfInBinary.numberOf2(-3) == 31;flag &= numberOfInBinary.numberOf2(-4) == 30;flag &= numberOfInBinary.numberOf2(-5) == 31;System.out.println(flag);}}`

《剑指Offer》  面试题10

0 0