classSolution { public: boolNearTwoPower(int n){ if (n <= 0) return1; n--; // 此处减一的目的是能够返回等于2的幂的数 n |= n >> 1; n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; return n + 1; //n = 00100000 // 00011111 (--) // 00001111 (>>1) //n = 00011111 //... } }
区间与的结果
1 2 3 4 5 6 7 8 9 10
classSolution {
public: intrangeBitwiseAnd(int left, int right){ while (left < right) { right -= right & -right; //每次去掉最右侧的1 } return right; } };