Regular Expression for Binary Numbers Divisible by 3

后端 未结 4 1525
没有蜡笔的小新
没有蜡笔的小新 2021-02-14 21:37

I am self-studying regular expressions and found an interesting practice problem online that involves writing a regular expression to recognize all binary numbers divisible by 3

4条回答
  •  名媛妹妹
    2021-02-14 21:42

    The problem you're encountering is that whilst your trick is (probably) valid, it doesn't map to a practical DFA (you have to track a potentially arbitrary difference between the number of even and odd ones, which would require an arbitrary number of states).

    An alternative approach is to note that (working from MSB to LSB) after the i-th character , x[i], your substring must either be equal to 0, 1, or 2 in modulo-3 arithmetic; call this value S[i]. x[i+1] must be either 0 or 1, which is equivalent to multiplying by 2 and optionally adding 1.

    So if you know S[i] and x[i+1], you can calculate S[i+1]. Does that description sound familiar?

提交回复
热议问题