Is this Java approach for checking alternating binary bits reasonable?

0
1
Asked By MellowPine_47 On

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

Answered By CobaltLynx8 On

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.

Answered By QuietMaple_62 On

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.

Answered By VividHarbor3 On

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

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.