주어진 작업은 N개의 요소가 있는 주어진 배열에서 연속적인 Automorphic 요소의 수를 최대화하는 것입니다.
자동형 숫자는 사각형이 숫자 자체와 같은 자릿수로 끝나는 숫자입니다. 예를 들어 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() 함수에서 int 유형의 변수 'n'을 만들고 여기에 주어진 배열의 크기를 저장합니다.
-
MaxAutomorphic 함수에서 현재 최대값과 지금까지의 최대값을 각각 저장하기 위해 int 유형의 CurrentMax=0 및 Maximum=0을 초기화합니다.
-
i=0에서 i
-
IsAutomophic() 함수에서 int 유형의 변수 sqr=n*n을 초기화하여 숫자 n의 제곱을 저장합니다.
-
조건이 n>0인 while 루프를 사용하여 루프를 만들고 n과 sqr의 마지막 숫자를 비교하여 숫자가 자동인지 여부를 확인합니다.
-
MaxAutomorphic() 함수로 돌아가서 number가 automorphic이 아니면 CurrentMax=0
으로 설정합니다. -
그렇지 않고 숫자가 자동으로 발견되면 CurrentMax에 1을 추가하고 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