c - C语言的棘手面试问题

标签 c puzzle

在以下面试问题中:

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 returning 3 and 5, for instance, return 4 and 4. 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/

相关文章:

java - 应该返回字符串中连续重复 3 次的字母数量,而不使用正则表达式...仅使用核心概念

vb.net - 基于网格的拼图棋盘游戏方 block 移除算法

c - 如果 a 是数组,函数 (1,a+2) 中的加法是什么意思?

c - Turbo C++ 调试问题

algorithm - 数组中的矩形区域

list - 从每个列表中最佳选择一个元素

C - strtok 返回更少的数据

c++ - Undefined reference to function错误,一起使用C和C++

c - 命令提示符的字符串搜索 C 程序

performance - Linq 解谜器