标签:
public class Solution { /** * @param num: an integer * @return: an integer, the number of ones in num */ /*** * Bit Opperation: * &: 1 & 1 = 1; 1 & 0 = 0; 0 & 0 = 0 * ~: ~1 = 0; ~0 = 1 * |: 1 | 1 = 1; 1 | 0 = 1; 0 | 0 = 0 * ^: 1 ^ 1 = 0; 1 ^ 0 = 1; 0 ^ 0 = 0 * <<: left shift 00000001 << 3 = 00001000 * >>: right shift The first bit is sign, it will got shift. * knowledge: http://sys.cs.rice.edu/course/comp314/10/p2/javabits.html ***/ public int countOnes(int num) { // write your code here int count = 0; for (int i = 0; i < 32; i++){ if ((num & (1 << i))!= 0){ //1 <<i only have one bit set to 1, the rest is 0, & will turn other bits to be 0. So whether it will 0 all counts on what "num" has on the same bit poistion. count++; } } return count; } };
标签:
原文地址:http://www.cnblogs.com/codingEskimo/p/4961806.html