1年前 (2018-08-10)  编程语言 |   抢沙发  7 
文章评分 0 次,平均分 0.0

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.

 

 

image

 

java 实现代码:

package com.zzy;

/**
 * 更多请关注: http://hadoopall.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;
        }
    }
}
 

除特别注明外,本站所有文章均为HadoopAll原创,转载请注明出处来自http://hadoopall.com/582.html

发表评论

表情 格式

暂无评论

登录

忘记密码 ?

切换登录

注册

扫一扫二维码分享