C++中求数字M个连续数字的最大和与积


本文给定一个表示数字的字符串。我们的任务是创建一个C++程序,找出给定数字中M个连续数字的最大和与积。我们找到所有长度为M的连续数字序列,并返回最大和与积。

在数学中,**连续数字**定义为按从小到大的顺序排列的数字,中间没有缺失的数字。

这个问题可以通过遍历数字的字符串表示来解决,换句话说,我们考虑长度为M的连续片段,计算片段中数字的和与积。

我们将始终检查之前遇到的最大和与最大积。如果我们循环遍历整个字符串,我们将得到M个连续数字的最大和与最大积。

**M个连续数字的最大和:**因此,各方应尽最大努力,如果可能,遍历M个连续数字的整个范围,其和是所有M位数序列中的最大值。

**M个连续数字的最大积:**同样地,它通过识别数字中积最大的M个数字来找到最大M位数组合。

让我们来看一下**输入和输出场景**,了解输入值如何与所需输出相关联:

输入

number = 2379641, M = 4

输出

maxSum = 26
maxProd = 1512

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

解释

这些都是给定的长度为4的子序列:2379, 3796, 7964, 和 9641。

最大和 = 7 + 9 + 6 + 4 = 26

最大积 = 7 * 9 * 6 * 4 = 1512

解决方案方法

解决这个问题的一个简单方法是从数字中找到所有可能的长度为M的连续子序列,然后将所有整数的值相加和相乘,并返回所有和与积值中的最大值。

示例

以下是C++程序,用于查找数字中M个连续数字的最大和与积:

Open Compiler
#include <iostream> using namespace std; int findMaxVal(int x, int y){ if(x > y) return x; return y; } void calcMaxProductAndSum(string number, int M){ int N = number.length(); int maxProd = -1, maxSum = -1; int product = 1; int sum = 0; for (int i = 0; i < N - M; i++){ product = 1, sum = 0; for (int j = i; j < M + i; j++){ product = product * (number[j] - '0'); sum = sum + (number[j] - '0'); } maxProd = findMaxVal(maxProd, product); maxSum = findMaxVal(maxSum, sum); } cout<<"The maximum product of "<<M<<" consecutive digits in number "<<number<<" is: "<<maxProd<<endl; cout<<"The sum of "<<M<<" consecutive digits in number "<<number<<" is: "<<maxSum; } int main() { string str = "2379641"; int m = 4; calcMaxProductAndSum(str, m); }

输出

The maximum product of 4 consecutive digits in number 2379641 is: 1512
The sum of 4 consecutive digits in number 2379641 is: 26

更新于:2024年5月22日

222 次浏览

开启你的职业生涯

完成课程获得认证

开始学习
广告