您的位置 首页 编程语言

java实现Write a method named isMadhavArray that returns 1

1. 美国面试试题2

A Madhav array has
the following property.
a[0] = a[1] + a[2] = a[3] + a[4] + a[5] = a[6] + a[7] + a[8] + a[9] = …
The length of a Madhav array must be n*(n+1)/2 for some n.
Write a method named isMadhavArray that returns 1 if its array argument is a Madhav array,
otherwise it returns 0. If you are programming in Java or C# the function signature is int isMadhavArray(int[ ] a)
If you are programming in C or C++, the function signature is
int isMadhavArray(int a[ ], int len) where len is the number of elements in a.

最后的测试用例为:

2 代码实现:

 

 

public class MadHavArray {
    public static void main(String[] args) {

//         int a[] = {2,1,1};
//        int a[] = {2, 1, 1, 4, -1, -1};
//        int a[] = {6, 2, 4, 2, 2, 2, 1, 5, 0, 0};
//        int a[] = {18, 9, 10, 6, 6, 6};
        int a[] = {-6, -3, -3, 8, -5, -4};//?
//        int a[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, -2, - 1};
//        int a[] = {3, 1, 2, 3, 0};
        System.out.println(isMadhavArray(a));
//        System.out.println(3/2);



    }

    public static int  isMadhavArray(int[]a){

        int length = a.length;


        int tmp=0;
        for (int i=0;i<length/2;i++){ // 判断长度是否满足条件 n*(n+1)/2
            int x = i*(i+1)/2;
            if (x ==length){
                tmp =1;
            }
        }
        if (tmp==0){
            return 0;
        }

        for (int i=1;i<=length/2;++i){
            int sum =0;
            for (int j = i*(i+1)/2 ; j< i+1;j++){ // a[2]+a[3] 和的实现
                sum = sum + a[j]+a[j+1];

            }
            if (sum != a[0]){
                return 0;
            }else {
                return 1;
            }
        }
        return 0;
    }
}

花猫大叔

铭记使命,不忘初心。

猫叔总结了 适合新手操作的副业 《淘宝虚拟产品月入2万的 6个 细分类目》的电子书 仅供参考

如果你对虚拟产品比较感兴趣,可以点击:

淘宝卖什么虚拟产品赚钱(月入2万+)

hadoopall

关于花猫大叔短视频创业 作者: hadoopall

热门文章

发表评论

电子邮件地址不会被公开。