回文计数 [英] Counting palindromes

查看:32
本文介绍了回文计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

The question was: A contest closes in n days hh hours, mm minutes and ss seconds. Given two values of n, how many palindromes of the format nhhmmss would we find in the indicated interval?

示例1

输入

1 2

输出

472

说明

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

We need to check the numbers 1000000 through 2235959 including only numbers where the last 6 digits correspond to times. We find 472 such numbers: 1000001, 1001001, 1002001, 1003001, 1004001, ..., 2231322, 2232322, 2233322, 2234322, 2235322

示例2

输入

0 2

输出

708

说明

有708个回文:0000000、0001000、0002000、0003000、0004000,...,2231312、2232322、2233322、2234322、2235322

There are 708 palindromes: 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;
}

但是它会抛出一个错误,如下所示:

But it is throwing an error as:

    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 为无效位置抛出异常.

The std::to_string function does not include leading zeros in the result. Your current code assumes the string is 7 digits but that might not be true and is likely why std::string::substr is throwing an exception for an invalid position.

这篇关于回文计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆