**Java**

```
class Solution {
public boolean hasAlternatingBits(int n) {
for (int prev = 1 - (n % 2); n > 0; prev = n % 2, n /= 2)
if (n % 2 == prev) return false;
return true;
}
}
```

**C++**

```
class Solution {
public:
bool hasAlternatingBits(int n) {
for (int prev = !(n % 2); n; prev = n % 2, n /= 2)
if (n % 2 == prev) return false;
return true;
}
};
```