Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

จำนวนตัวเลข Automorphic ติดต่อกันสูงสุดในอาร์เรย์ใน C++


ภาพรวมปัญหา

หาจำนวนตัวเลข Automorphic ที่ติดต่อกันมากที่สุดในอาร์เรย์

Automorphic Number: ตัวเลขที่ยกกำลังสองแล้วท้ายตรงกับตัวเลขเดิม (เช่น 5²=25, 6²=36, 25²=625)

ตัวอย่าง

Input: arr[] = {5, 3, 625, 6, 8, 1}
Output: 2
Explanation: Automorphic numbers: 5, 625, 6, 1
ติดต่อกันมากสุด: {625, 6} = 2 ตัว

Input: arr[] = {33, 25, 1, 76, 4}
Output: 3
Explanation: {25, 1, 76} ติดต่อกัน 3 ตัว

แนวทางแก้ปัญหา

  • ตรวจสอบแต่ละตัวเลขว่าเป็น Automorphic ไหม (เปรียบเทียบหลักท้ายของ n² กับ n)
  • นับลำดับติดต่อกัน: เจอ Automorphic -> เพิ่ม count, ไม่เจอ -> reset count
  • เก็บค่าสูงสุด

ตัวอย่างโค้ด C++

#include <bits/stdc++.h>
using namespace std;

bool IsAutomorphic(int n) {
    int sqr = n * n;
    while (n > 0) {
        if (n % 10 != sqr % 10) return false;
        n /= 10; sqr /= 10;
    }
    return true;
}

int MaxAutomorphic(int arr[], int size) {
    int CurrentMax = 0, Maximum = 0;
    for (int i = 0; i < size; i++) {
        if (!IsAutomorphic(arr[i]))
            CurrentMax = 0;
        else {
            CurrentMax++;
            Maximum = max(CurrentMax, Maximum);
        }
    }
    return Maximum;
}

int main() {
    int arr[] = { 33, 25, 1, 76, 4 };
    int size = sizeof(arr) / sizeof(arr[0]);
    cout << MaxAutomorphic(arr, size);
    return 0;
}

ผลลัพธ์

3