code.cpp 1.3 KB

12345678910111213141516171819202122232425262728293031
  1. /* You are to read each part of the date into its own integer
  2. ~ type variable. The year should be a 4 digit number.
  3. ~ You can assume the user enters a correct date (no error checking required).
  4. ~ Determine whether the entered date is a magic date.
  5. ~ Here are the rules for a magic date:
  6. mm * dd is a 1-digit number that matches the last digit of yyyy
  7. or
  8. mm * dd is a 2-digit number that matches the last 2 digits of yyyy
  9. or
  10. mm * dd is a 3-digit number that matches the last 3 digits of yyyy
  11. The program should then display true if the date is magic,
  12. or false if it is not.
  13. */
  14. bool magic(std::string str) {
  15. char space = ' ';
  16. std::size_t firstspace = str.find(space);
  17. // find position of the SPACE following firstspace
  18. std::size_t secondspace = str.find(space,firstspace+1);
  19. // the month is everything before firstspace
  20. int month = std::stoi(str.substr(0,firstspace));
  21. // the day is everything between firstspace and secondspace
  22. int day = std::stoi(str.substr(firstspace,(secondspace-firstspace)));
  23. // the year is everything after the secondspace
  24. std::string year = (str.substr(secondspace+1,4));
  25. int ears = year[3]-'0';
  26. int decade = std::stoi(year.substr(2,2));
  27. int century = std::stoi(year.substr(1,3));
  28. // md is a misdirection otherwise known as MONTH*DAY
  29. int md = month*day;
  30. return md==ears || md==decade || md==century;
  31. }