在 C++ 中查詢小於或等於 N 的數字中的最大乘積


假設,我們有一個整數 N > 0。任務是在小於或等於 N 的數字中找到最大的數字乘積。如果 N 是 390,則結果是 216,因為數字 389 正在生成最大的乘積 3 * 8 * 9 = 216。

要解決這個問題,我們將使用遞迴方法。所以,如果 N = 0,則返回 1,如果數字 N < 10,則返回 N,否則返回 max(max_product(N/10) * (N mod 10),max_product((N/10) - 1)*9)

示例

 線上演示

#include<iostream>
using namespace std;
int max_product(int N) {
   if (N == 0)
      return 1;
   if (N < 10)
      return N;
   return max(max_product(N / 10) * (N % 10), max_product(N / 10 - 1) * 9);
}
int main() {
   int N = 432;
   cout << "Maximum product is: " << max_product(N);
}

輸出

Maximum product is: 243

更新時間:19-12-2019

357 次瀏覽

啟動 職業生涯

完成課程獲得認證

開始
廣告