C语言的棘手面试问题
在下面的面试问题中:
给定一个数字n,给我这些数字 (其中
<前><代码>7 = 3 + 4 16 = 4 + 4 + 4 + 4 而不是 3 + 5 + 4 + 4 24 = 12 + 12 或 6 + 6 + 6 + 63..5
和偶数个 数字),其相加将返回 原始号码。结果数字 应尽可能平衡, 意味着不是返回3
和5
,例如,返回4
和 <代码>4。例如:
我想到了以下方法:
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;
}
}
}
}
但我仍然无法完成所有情况...当答案有不平衡解时我应该如何检查?
In the following interview question :
Given a number n, give me the numbers
(among3..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
I thought of the following method:
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;
}
}
}
}
but still I am not able to complete all the cases... How should I check when the answer has unbalanced solution??
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
C# 中的实现效率稍低
Slightly inefficient implementation in C#
这是我的解决方案,其中结果将完美平衡并检测不可能的情况:
该解决方案还将考虑数字 22 等情况,其中平衡除法给出 11+11(11 是无法使用给定的数字表示的数字)规则),细分将按 10+12 进行,然后是 5+5+6+6,最后是 5+5+3+3+3+3。
Here is my solution where the result will be perfectly balanced and with detection of impossible cases:
That solution will also take into account cases like the number 22 where the balanced division gives 11+11 (11 being a number that cannot be represented using the given rules), the subdivision will be done as 10+12, then 5+5+6+6 and finally 5+5+3+3+3+3.