การนับ palindromes [ซ้ำ]

Aug 15 2020

คำถามคือ: การแข่งขันจะปิดลงใน n วันชั่วโมงชั่วโมงมิลลิเมตรนาทีและวินาทีวินาที ด้วยค่า n สองค่าเราจะพบ palindromes ของรูปแบบ nhhmmss ได้กี่ค่าในช่วงเวลาที่ระบุ

ตัวอย่าง 1

อินพุต

1 2

เอาต์พุต

472

คำอธิบาย

เราต้องตรวจสอบตัวเลข 1000000 ถึง 2235959 รวมเฉพาะตัวเลขที่ 6 หลักสุดท้ายตรงกับเวลา เราพบ 472 หมายเลขดังกล่าว: 1000001, 1001001, 1002001, 1003001, 1004001, ... , 2231322, 2232322, 2233322, 2234322, 2235322

ตัวอย่าง 2

อินพุต

0 2

เอาต์พุต

708

คำอธิบาย

มี 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;
}

แต่มีข้อผิดพลาดเป็น:

    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มีข้อยกเว้นสำหรับตำแหน่งที่ไม่ถูกต้อง