Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Kiểm tra số điện thoại "fancy" (đẹp) C++

Số điện thoại 10 chữ số được gọi "fancy" nếu thỏa mãn ≥1 trong 3 điều kiện:

  1. Có 3 chữ số giống nhau liên tiếp (ví dụ: 555)
  2. Có 3 chữ số liên tiếp tăng/giảm dần (123 hoặc 321)
  3. Một chữ số xuất hiện ≥4 lần trong số

Ví dụ: 9859009976 → chữ số 9 xuất hiện 4 lần → fancy.

Giải thuật

  • Điều kiện 1,2: duyệt chuỗi, kiểm tra 3 ký tự liên tiếp
  • Điều kiện 3: mảng freq[10] đếm tần suất, kiểm tra freq[i] ≥ 4

Ví dụ minh họa

#include <iostream>
#include <string>
using namespace std;

bool consecutiveThreeSame(string s) {
    for (int i = 0; i + 2 < s.size(); i++)
        if (s[i] == s[i+1] && s[i+1] == s[i+2]) return true;
    return false;
}

bool incDecThree(string s) {
    for (int i = 0; i + 2 < s.size(); i++)
        if ((s[i] < s[i+1] && s[i+1] < s[i+2]) || (s[i] > s[i+1] && s[i+1] > s[i+2]))
            return true;
    return false;
}

bool fourOccurrence(string s) {
    int freq[10] = {0};
    for (char c : s) freq[c - '0']++;
    for (int i = 0; i < 10; i++) if (freq[i] >= 4) return true;
    return false;
}

bool isFancyNumber(string s) {
    return consecutiveThreeSame(s) || incDecThree(s) || fourOccurrence(s);
}

int main() {
    string s = "7609438921";
    cout << (isFancyNumber(s) ? "La so fancy" : "Khong phai so fancy");
}

Kết quả

La so fancy