您的位置 首页 编程语言

largestDifferenceOfEvens

Write a function named largestDifferenceOfEvens which returns the largest difference between even valued elements of its array argument. For example largestDifferenceOfEvens(new int[ ]{-2, 3, 4, 9}) returns 6 = (4 – (-2)). If there are fewer than 2 even numbers in the array, largestDifferenceOfEvens should return -1.
If you are programming in Java or C#, the function signature is
int largestDifferenceOfEvens(int[ ] a)
If you are programming in C or C++, the function signature is
int largestDifferenceOfEvens(int a[ ], int len) where len is the number of elements in the array a.

 

 

java 实现代码:

package com.zzy;

/**
 * 更多请关注: http://huamaodashu.com
 * Created by hadoopall on 10/08/2018.
 */
public class DifferenceOfEvens {
    public static void main(String[] args) {
//        int [] a = {1, 3, 5, 9};
//        int [] a = {1, 18, 5, 7, 33};
//        int [] a = {2, 2, 2, 2};
        int [] a = {1, 2, 1, 2, 1, 4, 1, 6, 4};

        System.out.println(largestDifferenceOfEvens(a));

    }

    public static int largestDifferenceOfEvens(int[] a){
        int maxEven  = 0;
        int minEven = 0;

        int count =0;

//        for (int i = 0; i < a.length; i++) {
//            if(isEven(a[i]) == 1){
//                 maxEven  = a[i];
//                 minEven = a[i];
//                break;
//            }
//        }
        for (int i = 0; i < a.length; i++) {
            if(isEven(a[i])==1){

                if(count == 0){
                    maxEven  = a[i];
                    minEven = a[i];
                }
                count++;
                if(a[i] > maxEven){
                    maxEven = a[i];
                }
                if(a[i] < minEven){
                    minEven = a[i];
                }
            }
        }
        if(count < 2){
            return -1;
        }else {
            return maxEven - minEven;
        }


    }


    public static int isEven(int a){
        if(a%2==0){
            return 1;
        }else {
            return 0;
        }
    }
}

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

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

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

hadoopall

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

热门文章

发表评论

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