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

更新於: 2020-08-17

242 次檢視

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.