C++ 中 11 位数字的数字的乘积

Product of the digits of an 11-digit number in c++

本文关键字:数字 C++      更新时间:2023-10-16

我正在编写一个关于乘法持久性的代码,我需要编写一个函数来计算数字中数字的乘积。这是一个基本函数,我已经写过了,但我已经意识到它无法计算任何超过 10 位数字的数字的乘积。如果数字有 11 位或更多数字,则无论输入什么数字,它都只会说"903168"。

这是它本身的样子:

#include <iostream>
using namespace std;
int main()
{
int a; int product = 1;
cout << "Enter a number: ";
cin >> a;
do  
{ 
product = product * (a % 10);
a = a / 10;
} 
while (a != 0);
cout << "The product of the digits of this number is: " << product;
}

还有其他人遇到过同样的问题吗?您知道如何修复它以便能够将此功能用于任何数字吗?

这是一种具有时间复杂度O(log n)的方法。递归有时可以降低时间复杂度。希望这对您的问题有所帮助!

int getPro(long int n) {
if (n==0)
return 1;
return (n%10)*getPro(n/10);
}

您需要使用较大的类型来保存输入编号和产品。在您的系统上,int几乎肯定是 32 位。让我们使用 64 位long long int

#include <iostream>
using namespace std;
int main()
{
long long int a; 
long long int product = 1;
cout << "Enter a number: ";
cin >> a;
do  
{ 
product = product * (a % 10);
a = a / 10;
} 
while (a != 0);
cout << "The product of the digits of this number is: " << product << endl;
}

现在:

% ./a.out
Enter a number: 12345678912
The product of the digits of this number is: 725760                           % ./a.out     
Enter a number: 99999999999
The product of the digits of this number is: 31381059609

修改上面的代码以避免using namespace std;并使用使位数更明显的类型。

#include <iostream>
#include <cstdint>
int main()
{
using std::cout;
using std::endl;
using std::cin;
int64_t a; 
int64_t product = 1;
cout << "Enter a number: ";
cin >> a;
do  
{ 
product *= a % 10;
a /= 10;
} 
while (a);
cout << "The product of the digits of this number is: " 
<< product
<< endl;
}