C++ 中求一个数中 M 个连续数字的最大和与乘积
c++server side programmingprogramming
本题中,给定一个表示数字的字符串。我们的任务是编写一个程序,用 C++ 求一个数中 M 个连续数字的最大和与乘积。
问题描述
我们求所有包含 M 个连续数字的序列。并返回最大和与乘积。
我们举个例子来理解这个问题:
输入
number = 2379641, M = 4
输出
maxSum = 26 maxProd = 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