在以下面试问题中:
Given a number n, give me the numbers (among
3..5
and an even number of numbers) whose adding would return the original number. The resulting numbers should be as balanced as possible, meaning that instead of returning3
and5
, for instance, return4
and4
. Ex: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;
}
}
}
}
但我仍然无法完成所有情况...当答案有不平衡解决方案时我应该如何检查?
最佳答案
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;
}
关于c - C语言的棘手面试问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5401052/