C#riddle:实现接口

时间:2009-11-10 16:51:49

标签: c#

更新:

这个问题不是作业。而不是防水的...... 我想讨论内部代表性。 当然:add1000应该加1000。

**请按照这个问题的精神回答......保持这种防水会使这个问题变得更长,没有任何理由...... ** 你可以击败纯十进制表示法 Changing internal representation in runtime 更新2:见

创建一个实现此接口的类型:

interface INumber
    {
        void add1000();
        void SetValue(decimal d);
        decimal GetValue();         
    }

所以我在这个for循环中尽可能快地从0到100亿(十亿美元,直到10e9)迭代:

private static void DoSomeAdding(INumber n)
        {
            Debug.Assert(n.GetValue()==0);

            for (long i=0; i<10000000000; i += 1000)
            {
                n.add1000();
            }

            Debug.Assert(n.GetValue() == 10000000000);

        }

所以你可以称之为:

DoSomeAdding(new YourNumberClass());

4 个答案:

答案 0 :(得分:13)

public Cheating : INumber
{
    static int timesCalled = 0;

    public void add1000() {}
    public void SetValue(decimal d) {}

    public decimal GetValue()
    {
        if (timesCalled == 0)
        {
            timesCalled += 1;
            return 0;
        }

        return 1000000000;
    }
}

答案 1 :(得分:6)

就像Anton的解决方案一样,但需要更加小心:)哦,我已经将名称更改为更像.NET。

public Number : INumber
{
    private decimal value = 0m;
    private int thousands = 0;

    public void Add1000()
    {
        thousands++;
    }

    void SetValue(decimal d)
    {
        value = d;
        thousands = 0;
    }

    decimal GetValue()
    {
        // Careful of the overflow... (do multiplication in decimal)
        value += thousands * 1000m;
        thousands = 0;
        return value;
    }
}

答案 2 :(得分:4)

public class JNumber : INumber
{
    decimal num = 0;

    public void add1000()
    {
        num = 10000000000;
    }

    public void SetValue(decimal d)
    {
    }

    decimal GetValue()
    {
        return num;
    }
}

...作弊,但过去了。

答案 3 :(得分:1)

我认为您需要更多要求。如上所述,最快的解决方案就是:

class MyNumberClass {
   bool is_ten_billion = false;
   int GetValue() {
      if(is_ten_billion) return 10000000000;
      is_ten_billion = true;
      return 0;
   }

   decimal add1000() {}

   void setValue(decimal d) {}
}

这样,优化器可以处理对add1000()的调用,然后完全处理对循环的调用。