# Java位运算总结-leetcode题目

 Operator Description & 按位与（12345&1=1，可用于判断整数的奇偶性） | 按位或 ^ 异或（同假异真） ~ 非（一元操作符） &=,|=,^= 合并运算和赋值 <>N 右移N位，（正数：高位补0，负数高位补1） >>>N 无符号右移（无论正负数，高位皆补0） <<=,>>=,>>>= 合并运算和赋值（移动相应位数再赋值给左边变量）

leetcode191:

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.

public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int num = 0;
do{
if((n & 1) == 1) num++;
}while((n>>>=1) > 0);
return num;
}

public static void main(String[] args){
System.out.println((new Solution()).hammingWeight(11));
}
}

Reverse bits of a given 32 bits unsigned integer.

For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as00111001011110000010100101000000).

If this function is called many times, how would you optimize it?

1     public int reverseBits(int n) {
2         int rs = 0;
3         for (int i = 0; i < 32; i++) {
4             rs = (rs << 1) + (n & 1);
5             n >>= 1;
6         }
7         return rs;
8     }

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

 1     public int reverse(int x) {
2         long l = new Long(x);
3         Long tmp = 0L;
4         while (l != 0) {
5             tmp = tmp * 10 + l % 10L;
6             l /= 10;
7         }
8         if (x > 0 && tmp > 2147483647L || x < 0 && tmp < -2147483648)
9             return 0;
10         return tmp.intValue();
11     }

posted @ 2015-03-31 20:02  xlturing  阅读(898)  评论(0编辑  收藏  举报