Advertisement
dscelab

p3

Apr 14th, 2025
530
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.00 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. if (c < '0' || c > '9') {
  11. cout << "Invalid input: Non-decimal character encountered!" << endl;
  12. return false;
  13. }
  14. int digit = c - '0'; // Convert char to int (e.g., '3' -> 3)
  15. switch (currentState) {
  16. case S0:
  17. break;
  18. case S1:
  19. break;
  20. case S2:
  21. break;
  22. currentState = static_cast<State>((0 * 10 + digit) % 3);
  23. currentState = static_cast<State>((1 * 10 + digit) % 3);
  24. currentState = static_cast<State>((2 * 10 + digit) % 3);
  25. }
  26. }
  27. // Accept if the FSM ends in state S0 (remainder 0, divisible by 3)
  28. return currentState == S0;
  29. }
  30. int main() {
  31. string input;
  32. cout << "Enter a decimal string: ";
  33. cin >> input;
  34. if (isDivisibleBy3(input)) {
  35. cout << "Accepted (the number is divisible by 3)" << endl;
  36. } else {
  37. cout << "Rejected (the number is not divisible by 3)" << endl;
  38. }
  39. return 0;
  40. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement