เนื่องจากภารกิจคือการเพิ่มจำนวนองค์ประกอบ Automorphic ที่ต่อเนื่องกันในอาร์เรย์ที่กำหนดโดยมีจำนวนองค์ประกอบ N จำนวน
ตัวเลขอัตโนมัติคือตัวเลขที่สี่เหลี่ยมจัตุรัสลงท้ายด้วยตัวเลขเดียวกับตัวตัวเลข ตัวอย่างเช่น 5 เป็นตัวเลขอัตโนมัติ เช่น 5*5 =25 และ 25 ลงท้ายด้วย 5.
ตอนนี้มาทำความเข้าใจสิ่งที่เราต้องทำโดยใช้ตัวอย่าง -
ป้อนข้อมูล − arr[]={5,3,625,6,8,1}
ผลผลิต − 2
คำอธิบาย − จำนวนออโตมอร์ฟิคที่มีอยู่ในอาร์เรย์ด้านบนคือ 5, 625, 6 และ 1 แต่ตัวเลขออโตมอร์ฟิคต่อเนื่องสูงสุดคือ {625,6} ซึ่งทำให้เอาต์พุต =2
ป้อนข้อมูล − arr[]={33, 25, 1, 76, 4}
ผลผลิต − 3
แนวทางที่ใช้ในโปรแกรมด้านล่างดังนี้
-
ในฟังก์ชัน main() ให้สร้างตัวแปร 'n' ของประเภท int และเก็บไว้ในนั้น ขนาดของอาร์เรย์ที่กำหนด
-
ในฟังก์ชัน MaxAutomorphic เริ่มต้น CurrentMax=0 และ Maximum=0 ทั้งสองประเภท int เพื่อเก็บค่าสูงสุดในปัจจุบันและค่าสูงสุดตามลำดับ
-
วนจาก i=0 จนถึง i
-
ในฟังก์ชัน IsAutomophic() ให้กำหนดค่าเริ่มต้นตัวแปร sqr=n*n ของประเภท int เพื่อเก็บกำลังสองของตัวเลข n
-
วนซ้ำโดยใช้ while loop โดยมีเงื่อนไข n>0 และเปรียบเทียบตัวเลขสุดท้ายของ n และ sqr เพื่อตรวจสอบว่าตัวเลขนั้นเป็นแบบอัตโนมัติหรือไม่
-
กลับไปที่ฟังก์ชัน MaxAutomorphic() หากตัวเลขไม่ใช่ automorphic ให้ตั้งค่า CurrentMax=0
-
มิฉะนั้น หากพบว่าตัวเลขเป็น automorphic ให้เพิ่ม 1 ใน CurrentMax และเก็บจำนวนที่มากกว่าจาก CurrentMax และ Maximum ลงในตัวแปร Maximum
ตัวอย่าง
#include <bits/stdc++.h>
using namespace std;
//Function to check if number is automorphic
bool IsAutomorphic(int n){
//Storing the square of n
int sqr = n * n;
//Comparing the digits
while (n > 0){
/*Return false if any digit of n doesn't
match with its square's last digits*/
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++){
//Checking if the element is non-automorphic
if (IsAutomorphic(arr[i]) == false)
CurrentMax = 0;
//Updating CurrentMax and Maximum if number is automorphic
else{
CurrentMax++;
Maximum = max(CurrentMax, Maximum);
}
}
return Maximum;
}
//Main function
int main(){
int arr[] = { 33, 25, 1, 76, 4 };
int size = sizeof(arr) / sizeof(arr[0]);
cout << MaxAutomorphic(arr, size);
return 0;
} ผลลัพธ์
หากเราเรียกใช้โค้ดข้างต้น เราจะได้ผลลัพธ์ดังต่อไปนี้ -
3