在 C++ 中查詢僅允許使用 2 個數字(和 7)的序列中的第 n 個元素


在這個問題中,我們給定一個整數 N,表示一個僅由 4 和 7 組成的數字序列。

該序列為 4、7、44、47、74、77、…

任務是查詢僅允許使用 2 個數字(和 7)的序列中的第 n 個元素。

讓我們舉一個例子來理解這個問題,

輸入

N = 4,

輸出

47

解釋

The series is: 4, 7, 44, 47, ….

解決方案方法

解決此問題的一個簡單方法是建立直到第 N 個數字的序列。如果當前數字的最後一位是 7,則很簡單。那麼前一個和後一個數字的最後一位是 4。

因此,我們將從第 1 個和第 2 個數字開始,然後繼續到下一個元素。

為此,我們將建立一個數組 series[n+1]。

For index series[1] put 4
For index series[2] put 7

然後對於直到 N 的後續值,找到給定索引 i 的值,

If i is odd, series[i] = series[i/2]*10 + 4
If i is even, series[i] = series[i/2]*10 + 7

經過 n 次迭代後,返回 series[n] 處的值。

程式說明了我們解決方案的工作原理,

示例

 即時演示

#include <iostream>
using namespace std;
int findNthSeriesElement(int N) {
   int series[N+1];
   series[1] = 4;
   series[2] = 7;
   for (int i=3; i<=N; i++) {
      if (i%2 != 0)
         series[i] = series[i/2]*10 + 4;
      else
         series[i] = series[(i/2)-1]*10 + 7;
   }
   return series[N];
}
int main() {
   int N = 9;
   cout<<"The "<<N<<"th element of the array is "<<findNthSeriesElement(N);
   return 0;
}

輸出

The 9th element of the array is 474

更新於: 2021年3月12日

182 次檢視

開啟你的職業生涯

透過完成課程獲得認證

開始
廣告

© . All rights reserved.