【问题标题】:What is the issue with this Stacked Number generating code?这个 Stacked Number 生成代码有什么问题?
【发布时间】:2016-07-10 12:31:16
【问题描述】:

这是我的作业:

将堆叠数定义为某个数的前 n 个正整数之和。前 5 个堆叠的数字是:

1 = 1
3 = 1 + 2
6 = 1 + 2 + 3
10 = 1 + 2 + 3 + 4
15 = 1 + 2 + 3 + 4 + 5

请注意,从上面我们可以推断出 7、8 和 9 不是堆叠数字,因为它们不能是从 1 开始的任何正整数序列的总和。编写一个名为 isStacked 的函数,如果它的参数返回 1是堆叠的。否则返回 0。它的签名是:

int isStacked(int n);

例如,isStacked(10) 应该返回 1,isStacked(7) 应该返回 0。

这是我的代码:

public class isStacked {
    public static void main(String[] arg) {
        System.out.println(isStacked(5));
        System.out.println(isStacked(6));
        System.out.println(isStacked(7));
        System.out.println(isStacked(45));
        System.out.println(isStacked(12));
    }

    static int isStacked(int a) {
        int b = 0;
        for (int i = 0; i <= a; i++) {
            b = b + i;
            if (b > a)
                break;
        }
        if (b == a)
            return 1;

        return 0;
    }
}

【问题讨论】:

  • 您意识到“堆叠数字”只是 triangle numbers 的另一个名称?
  • 您可以在 O(1) 时间内完成此操作,而不是 O(a)。定义n = floor(sqrt(2*a))。那么a 被堆叠当且仅当n*(n+1) == 2*a。 (检查溢出。)
  • 你指的“问题”是什么?

标签: java algorithm


【解决方案1】:

当您发现b == a 时,您应该从循环内返回true,因为如果您在b==a 时仍留在循环内,则在下一次迭代中b 将超过a,您将返回false。

static boolean isStacked(int a) {
    int b = 0;
    for (int i = 0; i <= a; i++) {
        b = b + i;
        if (b == a)
            return true;
        else if (b > a)
            return false;
    }
    return false;
}

除此之外,您应该使用boolean 作为返回类型,而不是int

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-07
    • 2014-08-29
    • 2013-06-05
    • 2014-06-04
    • 2011-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多