The question concerns writing regular expressions for binary strings.
How do you write one such that it ends with 00 and also another one such that it contains at least three 1's?
The question concerns writing regular expressions for binary strings.
How do you write one such that it ends with 00 and also another one such that it contains at least three 1's?
Ends with 00:
^[01]*00$
Contains at least three 1s:
^(?=.*(?:0*1){3})[01]*$
Both:
^(?=.*(?:0*1){3})[01]*00$
Explanation:
^ # Start of string
(?= # Assert that the following could be matched here:
.* # Any number of characters
(?:0*1) # followed by any number of 0s and exactly one 1
{3} # three times
) # End of lookahead
[01]* # Match any number of ones or zeroes
00 # Match two zeroes
$ # at the end of the string
Since the string may only contain ones and zeroes, we don't actually need to lookahead. The following will work as well (but only in these exact circumstances):
^(?:0*1){3}[01]*00$
* means "0 or more of the preceding token".Alternate solution not using a regex:
private static final BigInteger FOUR = new BigInteger("4");
public boolean binaryStringIsOK(final String input)
{
final BigInteger b;
try {
b = new BigInteger(inputString, 2);
return b.mod(FOUR).equals(BigInteger.ZERO)
&& b.bitCount() >= 3;
} catch (NumberException ignored) {
return false;
}
}
The "ends with 00" condition means that in base 10, it is a multiple of 4; therefore that the remainder of the integer division by 4 is 0. And the .bitCount() function does the rest.
An alternative to "ends with 00" is to test whether that number logical-and 3 is 0:
// THREE = new BigInteger("3")
b.and(THREE).equals(BigInteger.ZERO)