标签:unsigned its 二进制 present 整数 cti integer class number
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.
bit manipulation 操作很弱啊, 要把整数看作二进制数, 进行与、或、异或的运算
public int hammingWeight(int n) { if (n == 1) { return 1; } int res = 0; for (int i = 0; i < 32; ++i) { res += (n & 1); n = n >> 1; } return res; }
标签:unsigned its 二进制 present 整数 cti integer class number
原文地址:http://www.cnblogs.com/apanda009/p/7286935.html