Regular Expression for Binary Numbers Divisible by 3

后端 未结 4 1614
没有蜡笔的小新
没有蜡笔的小新 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:57

    Binary numbers divisible by 3 fall into 3 categories:

    1. Numbers with two consecutive 1's or two 1's separated by an even number of 0's. Effectively every pair "cancels" itself out.

    (ex. 11, 110, 1100,1001,10010, 1111)

    (decimal: 3, 6, 12, 9, 18, 15)

    1. Numbers with three 1's each separated by an odd number of 0's. These triplets also "cancel" themselves out.

    (ex. 10101, 101010, 1010001, 1000101)

    (decimal: 21, 42, 81, 69)

    1. Some combination of the first two rules (including inside one another)

    (ex. 1010111, 1110101, 1011100110001)

    (decimal: 87, 117, 5937)

    So a regular expression that takes into account these three rules is simply:

    0*(1(00)*10*|10(00)*1(00)*(11)*0(00)*10*)*0*

    How to read it:

    () encapsulate

    * means the previous number/group is optional

    | indicates a choice of options on either side within the parentheses

提交回复
热议问题