在这个问题中,我们得到了一个表示数字的字符串。我们的任务是创建一个程序,以查找C ++中一个数字中M个连续数字的最大和与乘积。
我们找到M个连续数字的所有序列。并返回最大和与乘积。
让我们举个例子来了解这个问题,
number = 2379641, M = 4
输出结果
maxSum = 26maxProd = 1512
大小为4的所有子序列均为2379、3796、7964、9641。maxSum = 7 + 9 + 6 + 4 = 26 maxProd = 7 * 9 * 6 * 4 = 1512
一个简单的解决方法是找到所有可能的大小为M的连续子序列。然后将整数的所有值相加并相乘,然后返回所有总和与乘积值的最大值。
该程序说明了我们解决方案的工作原理,
#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, 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 Product 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 Product of 4 consecutive digits in number 2379641 is 26