I'm a beginner programmer and wrote this Java method to determine whether an integer's binary representation has alternating 1s and 0s. Does this approach make sense, and are there any problems with it?
class Solution {
public boolean hasAlternatingBits(int n) {
double i = 1;
while (i < n) {
i *= 2;
if (i % 4 == 0) {
i++;
}
}
return (int) i == n && n != 2147483647;
}
}
3 Answers
Your idea appears to work by generating numbers with alternating bits, but it is much harder to understand than directly checking the bits. Also, `i` should not be a `double`; use an integer type. Alternating binary numbers can end in either 0 or 1, so it’s clearer to inspect adjacent bits rather than special-case values while constructing a candidate.
Another option is to take the last two bits and verify that every pair farther to the left is identical to them. However, the initial pair must be either `01` or `10`; pairs `00` and `11` are not alternating. In practice, comparing neighboring bits one at a time is easier to read and less error-prone.
A straightforward approach is to save the rightmost bit, shift the number right, and compare each next bit with the opposite of the previous one. If two adjacent bits match, return `false`; if the loop finishes, return `true`. For example:
boolean hasAlternatingBits(int n) {
int previous = n & 1;
n >>= 1;
while (n > 0) {
int current = n & 1;
if (current == previous) return false;
previous = current;
n >>= 1;
}
return true;
}
This handles numbers ending in either 0 or 1 without needing separate cases.

Related Questions
How To: Running Codex CLI on Windows with Azure OpenAI
Set Wordpress Featured Image Using Javascript
How To Fix PHP Random Being The Same
Why no WebP Support with Wordpress
Replace Wordpress Cron With Linux Cron
Customize Yoast Canonical URL Programmatically