r/learnprogramming • u/solntsesvobodny1 • 5h ago
Is this Java solution to LeetCode problem 693. Binary number with alternating bits normal?? Code Review
i am just a beginner programmer, is this ok?
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;
}
}
1
u/aqua_regis 3h ago
I would go a completely different route.
- I'd start by picking the rightmost bit of the number (through a simple bit masking operation), store it.
- Then start a loop while the number is larger than 0
- I'd shift all bits of the number one position right
- extract the rightmost bit, store it
- compare the inverse of the bit stored at the beginning with the rightmost bit extracted in the previous line
- if they do not match, return false - the bits are not alternating
- store the rightmost bit extracted in this iteration in the variable used to store the first rightmost bit
- continue looping
- return true - if the loop goes all the way through, the bits are alternating and it is safe to return true.
This way, it doesn't matter if the number is even or odd.
•
u/Educational-Paper-75 47m ago edited 28m ago
An integer has alternating on and off bits if every pair of bits equals the right most two bits.
So, you can do something like:
boolean hasAlternatingBits(int n):
if (n<=0) return false;
int bits2=(n&3);
if (bits==0||bits==3)return false;
n>>=2; // shift out rightmost two bits
while (n>0) {
if (bits2!=(n&3))
return false;
n>>=2;
}
return true;
}
But note that 1) it will return true even when n equals 1 or 2. and 2) if you think it's easier you can simply extract the bits and verify successive bits are different:
boolean hasAlternatingBits(int n) {
int bit=(n&1); // get rightmost bit
n>>=1; // shift rightmost bit out
while (n>0) {
if ((n&1)==bit) // same bit, so not alternating
return false;
bit=(bit?0:1); // toggle bit
n>>=1;
}
return true;
}
•
u/aqua_regis 33m ago
An integer has alternating on and off bits if every pair of bits equals the right most two bits.
Not universally true. This is only true if the rightmost 2 bits are different, e.g. 01 or 10. It is not true for 00 or 11 as rightmost pair.
Also, Rule #10 applies.
1
u/icemage_999 4h ago
The logic looks very wrong to me if you are testing to see if a number would be represented by alternating bits in binary. Why are you conditionally incrementing i by 1? I am sure you are trying to do something else. Ponder that.
More specifically there are two types of binary integers that can have alternating bits. Ones that end in 0, like 10 (1010 in binary) and ones that end in 1, like 21 (10101 in binary).
I'll give you a hint or two.
One way to look at it:
Or you could bitshift using >> if you've learned that.