问题描述
问题是: 比赛在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
任何帮助将不胜感激!
解决方法
std::to_string
函数的结果中不包含前导零。您当前的代码假定字符串为7位数字,但这可能不是正确的,并且很可能是std::string::substr
抛出无效位置异常的原因。