Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

ผลรวมสูงสุดและผลคูณของ M ตัวเลขติดกันใน C++

คำอธิบายปัญหา

ในปัญหานี้ เราได้รับสตริงที่แทนตัวเลข งานของเราคือสร้างโปรแกรมเพื่อหาผลรวมสูงสุดและผลคูณของ M ตัวเลขติดกันในตัวเลขใน C++

เราจะหาลำดับทั้งหมดของ 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