C++ 找出其数字与给定数字相乘的最小数字
(这里是初学者) 我的任务是找到一个最小的数字,它的数字与给定的数字相乘。如果无法使该数字输出“-1” 例如:C++ 找出其数字与给定数字相乘的最小数字,c++,c++11,C++,C++11,(这里是初学者) 我的任务是找到一个最小的数字,它的数字与给定的数字相乘。如果无法使该数字输出“-1” 例如: 10 = 25 2*5=10 13 = -1 5 = 5 100 = 455 4*5*5 = 100 输入为单个数字n; 0=2&&n>1;我——) { 而(n%i==0) { //保存分隔“n”的数字“i” //上架 数字推送(i); n=n/i; } } //如果为true,则不能形成数字“k” 如果(n!=1) 返回-1; //从堆栈“数字”中
10 = 25 2*5=10
13 = -1
5 = 5
100 = 455 4*5*5 = 100
输入为单个数字n;
0=2&&n>1;我——)
{
而(n%i==0)
{
//保存分隔“n”的数字“i”
//上架
数字推送(i);
n=n/i;
}
}
//如果为true,则不能形成数字“k”
如果(n!=1)
返回-1;
//从堆栈“数字”中弹出数字
//并将它们添加到“k”
长整型k=0;
而(!digits.empty())
{
k=k*10+位数。top();
digits.pop();
}
//所需最小数
返回k;
}
//上面要测试的驱动程序
int main()
{
long long int n;//我要转换的数字
cin>>n;
cout如果您的输入为0,那么它应该返回10而不是0如果您的输入为0,那么它应该返回10而不是0出现问题的网站在哪里?特别是,问题的完整规格是什么?它必须处理的数字大小的限制是什么?它是否告诉您哪个测试用例失败(根据测试用例ID,而不是输入)?你知道是否有一个测试用例通过了吗?@MaxVollmer:“一个只包含一个数字的序列的乘积就是这个数字本身。完全没有因子的乘积称为空积,等于1。”如果输入是5,答案是5,只是在竞赛系统中测试。如果我让5=-1,我只通过了7次测试,而不是9次。有问题的网站在哪里?特别是,问题的完整规格是什么?它必须处理的数字大小的限制是什么?它告诉你哪个测试用例失败了(通过测试用例ID,而不是输入)?你知道是否有一个测试用例通过了吗?@MaxVollmer:“一个只包含一个数字的序列的乘积就是这个数字本身。没有任何因素的乘积称为空乘积,等于1。”如果输入是5,答案是5,只是在竞赛系统中测试。如果我得到5=-1,我只通过了7次测试,而不是9次。哇,我不敢相信这是答案,非常感谢!哇,我不敢相信这是答案,非常感谢!
#include <iostream>
#include <stack>
using namespace std;
// function to find smallest number k such that
// the product of digits of k is equal to n
long long int smallestNumber(long long int n)
{
// if 'n' is a single digit number, then
// it is the required number
if (n >= 0 && n <= 9)
return n;
// stack the store the the digits
stack<long long int> digits;
// repeatedly divide 'n' by the numbers
// from 9 to 2 until all the numbers are
// used or 'n' > 1
for (long long int i = 9; i >= 2 && n > 1; i--)
{
while (n % i == 0)
{
// save the digit 'i' that divides 'n'
// onto the stack
digits.push(i);
n = n / i;
}
}
// if true, then no number 'k' can be formed
if (n != 1)
return -1;
// pop digits from the stack 'digits'
// and add them to 'k'
long long int k = 0;
while (!digits.empty())
{
k = k * 10 + digits.top();
digits.pop();
}
// required smallest number
return k;
}
// Driver program to test above
int main()
{
long long int n;//number i want to convert
cin >> n;
cout << smallestNumber(n);
return 0;
}