Suppose we have an array n that represents a binary representation of any number. We have to check whether its binary representation is divisible by three or not by using Deterministic Finite Automata DFA.
So, if the input is like n = [1, 1, 0, 0] (binary of 12), then the output will be True.
To solve this, we can construct DFA like below −
The approach is simple when a number is divisible by 3 then the remainder will be 0, if not then remainder will be 1 or 2. There are three states for these three remainders. The initial state is also final state because when remainder is 0 it means the number is divisible.
To solve this, we will follow these steps −
Let us see the following implementation to get better understanding −
def solve(nums): dfa_state = 0 for i in range(len(nums)): digit = nums[i] if dfa_state == 0: if digit == 1: dfa_state = 1 elif dfa_state == 1: if digit == 0: dfa_state = 2 else: dfa_state = 0 elif dfa_state == 2: if digit == 0: dfa_state = 1 if dfa_state == 0: return True return False n = [1, 1, 0, 0] print(solve(n))
[1, 1, 0, 0]