Hello! Tell me how to create an algorithm for the task or a flowchart?

The task:

The electronic clock shows the time in the format from 00:00 to 23:59. Count how many times a day it happens that a symmetric combination is shown to the left of the colon for the one to the right of the colon (for example, 02:20, 11:11, or 15:51).

    3 answers 3

    Because combinations are not very many, the problem can be solved by exhaustive search. I'll give the code in C ++, but I think it can be easily adapted for Java:

    #include <iostream> #include <iomanip> class Time { public: Time(int h, int m) : h_(h), m_(m) {} bool operator==(const Time& t) const { return h_ == t.h_ && m_ == t.m_; } bool operator!=(const Time& t) const { return !(*this == t); } Time& operator++() { if (++m_ == 60) { m_ = 0; if (++h_ == 24) { h_ = 0; } } return *this; } bool isSymetric() const { int d1 = h_ / 10; int d2 = h_ % 10; int d3 = m_ / 10; int d4 = m_ % 10; return d1 == d4 && d2 == d3; } int h() const { return h_; } int m() const { return m_; } private: int h_; int m_; }; std::ostream& operator<<(std::ostream& os, const Time& time) { char prev = os.fill('0'); os << std::setw(2) << time.h() << ':' << std::setw(2) << time.m(); os.fill(prev); return os; } int main() { Time time(0, 0); do { if (time.isSymetric()) { std::cout << time << std::endl; } } while (++time != Time(0, 0)); } 

    Result:

     00:00 01:10 02:20 03:30 04:40 05:50 10:01 11:11 12:21 13:31 14:41 15:51 20:02 21:12 22:22 23:32 

      It turns out that a combination of symmetric can only when the internal digit (the one near the colon) is less than six - we have [00; 05] U [10; 15] U [20; 23] => 6 + 6 + 4 = 16 times. Although there may be some more elegant method.

        it seems easier nowhere to loop 24 iterations

          int x, y; final StringBuilder b = new StringBuilder ( 5 ); // for each hour: reverse hour value to get minutes for ( int i = 0; i < 24; i++ ) // hours 0-23 { x = i / 10; y = i % 10; // filter invalid minutes value if ( y > 5 ) { continue; } // [10*x]+[y]:[10*y]+[x] b.append ( x ).append ( y ).append ( ":" ).append ( y ).append ( x ); System.out.println ( b ); b.setLength ( 0 ); }