Advertisement
dscelab

p2

Apr 14th, 2025
478
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.06 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3. using namespace std;
  4. enum State {
  5. S0, S1, S2
  6. };
  7. bool isDivisibleBy3(const string& input) {
  8. State currentState = S0; // Start in state S0 (remainder = 0)
  9. for (char c : input) {
  10. switch (currentState) {
  11. case S0:
  12. if (c == '0') {
  13. currentState = S0; // Stay in S0 (remainder 0)
  14. } else if (c == '1') {
  15. currentState = S1; // Move to S1 (remainder 1)
  16. }
  17. break;
  18. case S1:
  19. if (c == '0') {
  20. currentState = S2; // Move to S2 (remainder 2)
  21. } else if (c == '1') {
  22. currentState = S0; // Move to S0 (remainder 0)
  23. }
  24. break;
  25. case S2:
  26. if (c == '0') {
  27. currentState = S1; // Move to S1 (remainder 1)
  28. } else if (c == '1') {
  29. currentState = S2; // Stay in S2 (remainder 2)
  30. }
  31. break;
  32. }
  33. }
  34. // Accept if the FSM ends in state S0 (remainder 0, divisible by 3)
  35. return currentState == S0;
  36. }
  37. int main() {
  38. string input;
  39. cout << "Enter a binary string: ";
  40. cin >> input;
  41. if (isDivisibleBy3(input)) {
  42. cout << "Accepted (the number is divisible by 3)" << endl;
  43. } else {
  44. cout << "Rejected (the number is not divisible by 3)" << endl;
  45. }
  46. return 0;
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement