C++ 中最大化连续自守数的数量
给定任务是在具有 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() 函数中创建一个 int 类型的变量 'n',并在其中存储给定数组的大小。
在 MaxAutomorphic 函数中初始化 CurrentMax=0 和 Maximum=0,它们都是 int 类型,分别用于存储当前最大值和迄今为止的最大值。
循环从 i=0 到 i<n,并通过调用 IsAutomorphic() 函数检查给定数字是否为自守数。
在 IsAutomophic() 函数中初始化一个 int 类型的变量 sqr= n*n 以存储数字 n 的平方
使用 while 循环并使用条件 n>0 进行循环,并比较 n 和 sqr 的最后一位数字以检查数字是否为自守数。
返回 MaxAutomorphic() 函数,如果数字不是自守数,则设置 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
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP