C++ 中 11 位数字的数字的乘积
Product of the digits of an 11-digit number in c++
我正在编写一个关于乘法持久性的代码,我需要编写一个函数来计算数字中数字的乘积。这是一个基本函数,我已经写过了,但我已经意识到它无法计算任何超过 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;
}
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 检查输入是否不是整数或数字
- 如何(从固定列表中)选择一个数字序列,该序列将与目标数字相加
- 如何用数字处理log(0)
- 最高有效数字侧的第N位
- 如何获取一个数字的前3位
- 查找最接近的大于当前数字的数字的索引
- 找到两对数字,使它们的乘积的绝对差最小化
- 我想做一个彼此不同但重复出现的数字
- 将数字转换为字母(例如:123 转换为一二三)
- C++如何计算用户输入的数字中的偶数位数
- 如何在C++中确定文本文件中的元素是字符还是数字
- 打印数字图案
- C++问题:用户认为数字1-100,程序提出问题不超过6次即可得到答案。无法正确
- 如何检查一个c++字符串中有多少相同的字符/数字
- 求出有多少个数字是完美平方,而sqrt()是L,R范围内的素数
- 将数字打印成文字
- 当使用比格式支持的精度更高的精度来显示数字时,会写出什么数据
- 在将数字随机生成为数组期间从内存输出随机数的数组