回文を数える[重複]

Aug 16 2020

質問は次のとおりです。コンテストはn日、hh時間、mm分、ss秒で終了します。nの値が2つあるとすると、指定された間隔でnhhmmss形式の回文がいくつ見つかりますか?

例1

入力

1 2

出力

472

説明

最後の6桁が時間に対応する番号のみを含め、1000000から2235959までの番号を確認する必要があります。1000001、1001001、1002001、1003001、1004001、...、2231322、2232322、2233322、2234322、2235322のような472の番号が見つかります

例2

入力

0 2

出力

708

説明

708回文があります:0000000、0001000、0002000、0003000、0004000、...、2231322、2232322、2233322、2234322、2235322

私が試したのは:

#include <bits/stdc++.h>

using namespace std;

#define endl "\n"
#define int long long

int ctr = 0;

int isPal(int n) {
    int reverse = 0;

    for(int i = n; i > 0; i /= 10)
        reverse = reverse*10 + i%10;

    return n == reverse; 
}

void inRange(int low, int high) {
     for (int i = low; i <= high; i++) {
          if (isPal(i)) {
             string tmp_str = to_string(i);
             string hh = tmp_str.substr(1, 2);
             string mm = tmp_str.substr(3, 2);
             string ss = tmp_str.substr(5, 2);
             int hh1, mm1, ss1;

             hh1 = stoi(hh);
             mm1 = stoi(mm);
             ss1 = stoi(ss);

             if (hh1 <= 23 && mm1 <=59 && ss1 <=59)
                 ctr++;
          }
     }
}

int main() {
    ios::sync_with_stdio(0); 
    cin.tie(0); 
    cout.tie(0);

    int n1, n2, min, max;

    cin >> n1 >> n2;

    min = n1*1000000;
    max = (n2*1000000)+235959;

    inRange(min,max);

    if (n1 == 0)
       cout << (ctr+99);
    else
        cout << ctr;

    return 0;
}

しかし、次のようなエラーがスローされます。

    terminate called after throwing an instance of 'std::out_of_range'
  what():  basic_string::substr: __pos (which is 3) > this->size() (whic
h is 1)
exited, aborted

どんな助けでもいただければ幸いです!

回答

1 Blastfurnace Aug 15 2020 at 23:40

このstd::to_string関数は、結果に先行ゼロを含めません。現在のコードでは、文字列が7桁であると想定していますが、それは正しくない可能性がstd::string::substrあり、無効な位置に対して例外をスローしている可能性があります。