Ask Your Question
3

How to calculate the product of the digits of an 11-digit number using c++?

asked 2022-05-28 11:00:00 +0000

scrum gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2021-04-20 16:00:00 +0000

djk gravatar image

There are different ways to calculate the product of the digits of an 11-digit number using c++. One approach is to convert the number to a string, iterate through each character of the string, convert it back to an integer, and multiply the digits together. Here's an example code:

#include <iostream>
#include <string>

using namespace std;

int main() {
    long long number = 12345678901; // example 11-digit number
    string str = to_string(number);
    int product = 1;
    for (char c : str) {
        int digit = c - '0';
        product *= digit;
    }
    cout << "The product of the digits of " << number << " is " << product << endl;
    return 0;
}

In this code, we first define the 11-digit number as a long long integer. We then convert it to a string using the to_string function. We initialize the product variable to 1, and we iterate through each character of the string using a for-each loop. For each character, we subtract the ASCII code of '0' to get the actual digit value, and we multiply it with the current value of the product variable. Finally, we print out the result of the product.

Note that if the number has leading zeros, they will be ignored by the conversion to string. In that case, you might need to pad the string with zeros before computing the product.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-05-28 11:00:00 +0000

Seen: 19 times

Last updated: Apr 20 '21