classSolution{public:boolhasAlternatingBits(intn){// n = 0b010101// n >> 2 = 0b000101// n ^ (n >> 2) = 0b010000 = a// a - 1 = 0b001111// a & (a - 1) = 0constinta=n^(n>>2);return(a&(a-1))==0;}};
1 2 3 4 5 6 7 8 91011
classSolution{publicbooleanhasAlternatingBits(intn){// n = 0b010101// n >> 2 = 0b000101// n ^ (n >> 2) = 0b010000 = a// a - 1 = 0b001111// a & (a - 1) = 0finalinta=n^(n>>2);return(a&(a-1))==0;}}
123456789
classSolution:defhasAlternatingBits(self,n:int)->bool:# n = 0b010101# n >> 2 = 0b000101# n ^ (n >> 2) = 0b010000 = a# a - 1 = 0b001111# a & (a - 1) = 0a=n^(n>>2)return(a&(a-1))==0