【问题标题】:Int instead of Long, bug?Int 而不是 Long,错误?
【发布时间】:2015-10-02 16:15:16
【问题描述】:

我在 Codility 执行任务(其内容在下面的链接中)。 我不明白为什么它会给出不同的结果:

1) 80%

public int solution(int[] A)
{
    long total = ((2+A.Length)*(A.Length+1)/2);
    long sum=0L;

    for(int i=0;i<A.Length;i++)
    {
        sum+=A[i];
    }

    return (int)(total-sum);
}

2) 100%

public int solution(int[] A)
{
    long N=A.Length+1;
    long total = N*(N+1)/2;
    long sum=0L;

    for(int i=0;i<A.Length;i++)
    {
        sum+=A[i];
    }

    return (int)(total-sum);
}

它似乎将结果视为 System.Int32 并且它是 System.Int64,我已经在 VS 中检查过它。这是一个错误,还是我错过了什么?

【问题讨论】:

  • 代码示例应该在问题本身中,而不是在外部链接中。

标签: c# algorithm int long-integer


【解决方案1】:

T[].Length 是一个intT[].LongLengthlong

试试这段代码,其中checked 表示算术溢出应该导致异常:

long total = checked((A.Length + 2) * (A.Length + 1) / 2);

您应该获得OverflowException,因为即使A.Length 的大小不超过int,产品也会。当您将代码更改为:

long N = A.Length + 1;
long total = N * (N + 1) / 2;

您现在使用long 而不是int 进行乘法运算,因此不会溢出。

此代码也可以正常工作,即使我更喜欢单独定义 N 的版本:

long total = (A.LongLength + 2) * (A.LongLength + 1) / 2;

【讨论】:

    【解决方案2】:

    在这里:

    long total = ((2+A.Length)*(A.Length+1)/2);
    

    A.Lengthint,乘法可能会溢出。因此,在结果已经可能溢出后,您将结果存储到 long

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-27
      • 2010-12-26
      相关资源
      最近更新 更多