Number of 1 Bits

来源:互联网 发布:工业控制网络安全性 编辑:程序博客网 时间:2024/04/28 20:01

1 Java位运算

public class Test {    public static void main(String[] args) {        // 1、左移( << )        // 0000 0000 0000 0000 0000 0000 0000 0101 然后左移2位后,低位补0://        // 0000 0000 0000 0000 0000 0000 0001 0100 换算成10进制为20        System.out.println(5 << 2);// 运行结果是20        // 2、右移( >> ) 高位补符号位        // 0000 0000 0000 0000 0000 0000 0000 0101 然后右移2位,高位补0:        // 0000 0000 0000 0000 0000 0000 0000 0001        System.out.println(5 >> 2);// 运行结果是1        // 3、无符号右移( >>> ) 高位补0        // 例如 -5换算成二进制后为:0101 取反加1为1011        // 1111 1111 1111 1111 1111 1111 1111 1011        // 我们分别对5进行右移3位、 -5进行右移3位和无符号右移3位:        System.out.println(5 >> 3);// 结果是0        System.out.println(-5 >> 3);// 结果是-1        System.out.println(-5 >>> 3);// 结果是536870911        // 4、位与( & )        // 位与:第一个操作数的的第n位于第二个操作数的第n位如果都是1,那么结果的第n为也为1,否则为0        System.out.println(5 & 3);// 结果为1        System.out.println(4 & 1);// 结果为0        // 5、位或( | )        // 第一个操作数的的第n位于第二个操作数的第n位 只要有一个是1,那么结果的第n为也为1,否则为0        System.out.println(5 | 3);// 结果为7        // 6、位异或( ^ )        // 第一个操作数的的第n位于第二个操作数的第n位 相反,那么结果的第n为也为1,否则为0         System.out.println(5 ^ 3);//结果为6         // 7、位非( ~ )        // 操作数的第n位为1,那么结果的第n位为0,反之。        System.out.println(~5);// 结果为-6     } }

2. 题目

Write a function that takes an unsigned integer and returns the number of ’1’ bits it has (also known as the Hamming weight).

For example, the 32-bit integer ’11’ has binary representation 00000000000000000000000000001011, so the function should return 3.

2.1 偷懒的方法

public class Solution {    // you need to treat n as an unsigned value    public int hammingWeight(int n) {        String s = Integer.toBinaryString(n);        int count = 0;        for(int i=0; i<s.length();i++){            if(s.charAt(i) == '1')                count++;        }        return count;    }}

2.2 自己实现Integer.toBinaryString(n)方法

    //无符号整数转为二进制字符串    public String int2binaryString(int n) {        char[] bs = new char[32];        for(int i=0; i<32; i++){            bs[i] = 0;        }        char[] binary = {'0','1'};        int i = 32;        int mask = 1;        int digit;        while(n != 0){            digit = n & mask;            bs[--i] = binary[digit];            //这里的无符号位移是关键,要记住            n = n >>> 1;        }        return new String(bs);    }
0 0