首页 > 解决方案 > 计数回文

问题描述

问题是:比赛在 n 天 hh 小时、mm 分钟和 ss 秒后结束。给定两个 n 值,我们会在指定的区间内找到多少个 nhhmmss 格式的回文?

示例 1

输入

1 2

输出

472

解释

我们需要检查从 1000000 到 2235959 的数字,仅包括最后 6 位数字对应于时间的数字。我们找到了 472 个这样的数字:1000001、1001001、1002001、1003001、1004001、...、2231322、2232322、2233322、2234322、2235322

示例 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

任何帮助,将不胜感激!

标签: c++

解决方案


std::to_string函数在结果中不包括前导零。您当前的代码假定字符串是 7 位数字,但这可能不是真的,这可能是为什么std::string::substr会为无效位置抛出异常。


推荐阅读