Regular Expression for Binary Numbers Divisible by 3

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

    I have another way to this problem and I think this is easier to understand. When we are dividing a number by 3 we can have three remainders: 0, 1, 2. We can describe a number which is divisible by 3 using expression 3t (t is a natural number).


    When we are adding 0 after a binary number whose remainder is 0, the actual decimal number will be doubled. Because each digit is moving to a higher position. 3t * 2 = 6t, this is also divisible by 3.

    When we are adding a 1 after a binary number whose remainder is 0, the actual decimal number will be doubled plus 1. Because each digit is moving to a higher position followed by a 1; 3t * 2 + 1 = 6t + 1, the remainder is 1.


    When we are adding a 1 after a binary number whose remainder is 1. The actual decimal number will be doubled plus one, and the remainder is 0; (3t + 1)*2 + 1 = 6t + 3 = 3(2t + 1), this is divisible by 3.

    When we are adding a 0 after a binary number whose remainder is 1. The actual decimal number will be doubled. And the remainder will be 2. (3t + 1)*2 = 6t + 2.


    When we are adding a 0 after a binary number whose remainder is 2. The remainder will be 1. (3t + 2)*2 = 6t + 4 = 3(2t + 1) + 1

    When we are adding a 1 after a binary number whose remainder is 2. Then remainder will still be 2. (3t + 2)*2 + 1 = 6t + 5 = 3(2t + 1) + 2.

    No matter how many 1 you add to a binary number whose remainder is 2, remainder will be 2 forever. (3(2t + 1) + 2)*2 + 1 = 3(4t + 2) + 5 = 3(4t + 3) + 2


    So we can have the DFA to describe the binary number: DFA describing binary numbers divisible by 3

    Note: Edge q2 -> q1 should be labelled 0.

提交回复
热议问题