【oj每周推荐】(算法)各位乘积
给出整数N(0 ≤ N ≤ 10^9),找出一个最小的整数Q,使得将Q的每一位相乘之后等于N
例如N=18,则Q可能取值为:29(2×9=18),36(3×6=18),63(6×3=18),92(9×2=18)
那么我们只要取最小值29即为结果
输入:整数N(0 ≤ N ≤ 10^9)
输出:如果存在这样的Q,则输出Q,如果不存在,输出-1
------解决方案-------------------- string sTemp = "";
int temp = N;
int count2 = two(ref temp);
int count3 = three(ref temp);
int count5 = five(ref temp);
int count7 = seven(ref temp);
if (temp > 9)
{
Q = "-1";
return;
}
int count8 = 0;
int count4 = 0;
int count9 = 0;
int count6 = 0;
while (count3 >= 2)
{
count9++;
count3 = count3 - 2;
}
if (count3 == 1 && count2 > 0)
{
count3 = 0;
count2 = count2 - 1;
count6 = 1;
}
while (count2 >= 3)
{
count8++;
count2 = count2 - 3;
}
if (count2 == 2)
{
count4 = 1;
count2 = 0;
}
else if (count2 == 1)
{
count2 = 1;
}
else
{
count2 = 0;
}
for (int i = 0; i < count2; i++)
{
sTemp = sTemp + "2";
}
for (int i = 0; i < count3; i++)
{
sTemp = sTemp + "3";
}
for (int i = 0; i < count4; i++)
{
sTemp = sTemp + "4";
}
for (int i = 0; i < count5; i++)
{
sTemp = sTemp + "5";
}
for (int i = 0; i < count6; i++)
{
sTemp = sTemp + "6";
}
for (int i = 0; i < count7; i++)
{
sTemp = sTemp + "7";
}
for (int i = 0; i < count8; i++)
{
sTemp = sTemp + "8";
}
for (int i = 0; i < count9; i++)
{
sTemp = sTemp + "9";
}
Q = int.paser(sTemp );
------解决方案-------------------- private long t(long N)
{
long r = 0;
for (long m = 1, i = 9; i > 1; i--)
{
while ((N % i) == 0)
{
r += m * i;
m *= 10;
N /= i;
}
}
return r == 0 && N != 0 ? -1 : r;
}
------解决方案--------------------22楼已经说到了好的方法,我总结下,再可以优化下,但第一次是必须使用9到2分别试除一遍的,不然没法取最小整数。
整理后的代码如下:
C# code
public static void test(int n)
{
if (n < 0) Console.WriteLine(-1);
else
{
List<int> num = new List<int>();
List<int> q = new List<int>();
//从大到小初始化列表num
for (int i = 9; i > 1; i--)
{
num.Add(i);
}
//从最大的数开始查找是否可以整除,排除不可整除的,记录可以整除的。
while (num.Count > 0)
{
if (n % num[0] == 0)
{
n = n / num[0];
q.Add(num[0]);
}
else
num.Remove(num[0]);
}
//如果最后n为1,说明完全被整除,对记录的各个除数列表排序后输出,得到最小整数,否则输出-1,没有找到
if (n == 1)
{
q.Sort();
foreach (int i in q)
{
Console.Write(i);
}
Console.WriteLine();
}
else
Console.WriteLine(-1);
}
}