class Solution { public: boolhasAlternatingBits(int n){ vector<int> bits; while(n) { bits.push_back(n & 1); n >>= 1; } for(int i = 0; i < bits.size() - 1; i++) { if(bits[i] == bits[i + 1]) { returnfalse; } } returntrue; } };
Version 2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
class Solution { public: boolhasAlternatingBits(int n){ int pre = - 1; while(n) { int current = n & 1; if(pre != -1 && pre == current) { returnfalse; } n >>= 1; pre = current; } returntrue; } };