题目
In this kata, your task is to create a regular expression capable of evaluating binary strings (strings with only 1
s and 0
s) and determining whether the given string represents a number divisible by 3.
Take into account that:
- An empty string might be evaluated to true (it's not going to be tested, so you don't need to worry about it - unless you want)
- The input should consist only of binary digits - no spaces, other digits, alphanumeric characters, etc.
- There might be leading
0
s.
Examples (Javascript)
-
multipleof3Regex.test('000')
should betrue
-
multipleof3Regex.test('001')
should befalse
-
multipleof3Regex.test('011')
should betrue
-
multipleof3Regex.test('110')
should betrue
-
multipleof3Regex.test(' abc ')
should befalse
You can check more in the example test cases
Note
There's a way to develop an automata (FSM) that evaluates if strings representing numbers in a given base are divisible by a given number. You might want to check an example of an automata for doing this same particular task here.
If you want to understand better the inner principles behind it, you might want to study how to get the modulo of an arbitrarily large number taking one digit at a time.
我的答案
PATTERN = re.compile(r'^((((0+)?1)(10*1)*0)(0(10*1)*0|1)*(0(10*1)*(1(0+)?))|(((0+)?1)(10*1)*(1(0+)?)|(0(0+)?)))$')
这道题真没想出来,参考大神的答案
其他精彩答案
PATTERN = re.compile(r'^(0|1(01*0)*1)*$')
'''
000 => 0 True
001 => 1 False
011 => 3 True
111 => 7 False
1100 = True
R = Q + RP => R = QP*
A = 1B + 0A
B = 1A + 0C
C = 1C + 0B
C = 1C + 0B => C => 1*0B
B = 1A + 0C => B = 01*0B + 1A => B = (01*0)*1A
A = 1B + 0A => A = 1(01*0)*1A + 0A => (1(01*0)*1|0)*
'''
PATTERN = re.compile(r'^([1]([0][1]*[0])*[1]|[0])*$')