在下面的面试问题中:
给出数字n,给我数字 (在
3..5
和偶数之间 数字)其添加将返回 原始号码。由此产生的数字 应该尽可能平衡, 意思是代替返回3
例如,5
返回4
和4
。例如:7 = 3 + 4 16 = 4 + 4 + 4 + 4 rather than 3 + 5 + 4 + 4 24 = 12 + 12 or 6 + 6 + 6 + 6
我想到了以下方法:
splitnumber(int n)
{
//check if the number is even
if(n%2==0)
{
print(n/2,n/2);
//check if x=2^m multiple exists or
// not..like 4,8,16 etc
print (n/x...n/x);
}
else //else if the no is odd... this part is incomplete
{
if(n-3>0)
{
print (3);
}
n-=3;
if(n>0)
{
if (n>5)
{
print(3)
n-=3;
}
}
}
}
但我仍然无法完成所有案例......如何在答案出现不平衡的解决方案时检查?
答案 0 :(得分:1)
if (n < 4) print n;
else
switch (n % 4)
case 0: *print n/4 4's*
case 1: *print n/4 - 1 4's* print 5
case 2: *print n/4 - 1 4's* print 3 print 3
case 3: *print n/4 4's* print 3
在C#
中执行效率稍差if (n < 4) Console.WriteLine(n);
else
switch (n % 4)
{
case 0:
Console.WriteLine(String.Join(" ", new string('4', n / 4).ToArray()));
break;
case 1:
Console.WriteLine(
(String.Join(" ", new string('4', n/4).ToArray().Skip(1)) +
" 5").TrimStart());
break;
case 2:
Console.WriteLine(
(String.Join(" ", new string('4', n/4).ToArray().Skip(1)) +
" 3 3").TrimStart());
break;
case 3:
Console.WriteLine(String.Join(" ", new string('4', n/4).ToArray() +
" 3"));
break;
}
答案 1 :(得分:1)
这是我的解决方案,其结果将完美平衡并检测不可能的情况:
vector<int> recursive_splitnumber(int n) {
if (n <= 5) {
return vector<int>(1,n);
}
int unbalancer = 0;
vector<int> result1, result2;
do {
int val1, val2;
if (n%2 == 0) {
val1 = n%2 + unbalancer;
val2 = n%2 - unbalancer;
}
else {
val1 = (n-1)%2 + 1 + unbalancer;
val2 = (n-1)%2 - unbalancer;
}
result1 = recursive_splitnumber(val1);
result2 = recursive_splitnumber(val2);
// Concatenate the result of the even and odd splits
result1.insert(result1.end(),result2.begin(),result2.end());
++unbalancer;
} while (result1.size()%2 != 0 && unbalancer <= 1);
return result1;
}
bool splitnumber(int n) {
vector<int> split = recursive_splitnumber(n);
if (split.size()%2 == 0) {
copy(split.begin(), split.end(), ostream_iterator<int>(cout, " "));
return true;
} else
return false;
}
该解决方案还将考虑数字22的情况,其中平衡除法给出11 + 11(11是无法使用给定规则表示的数字),细分将以10 + 12,然后5 + 5 + 6 + 6,最后是5 + 5 + 3 + 3 + 3 + 3。