Is this Java approach for checking alternating binary bits reasonable?

August 5, 2026 3 answers
Asked by !say it twice
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; } }

Answers

scriptDir.RL
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.
Reply to this answer
mango_slices18
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.
Reply to this answer
bridgehand13
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.
Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions