在 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP