An array is zero-plentiful if it contains at least one 0 and every sequence of 0s is of length at least 4.
Write a method named isZeroPlentiful which returns the number of zero sequences if its array argument is zero-plentiful, otherwise it returns 0.
If you are programming in Java or C#, the function signature is
int isZeroPlentiful(int[ ] a)
If you are programming in C or C++, the function signature is
int isZeroPlentiful(int a[ ], int len) where len is the number of elements in the array a.
java实现代码:
package com.zzy;
/**
* 更多请关注: http://huamaodashu.com
* Created by huamaodashu on 31/07/2018.
*/
public class ZeroPlentiful {
public static void main(String[] args) {
// int[] a = {1, 2, 0, 0, 0,0,0,0,0,0,0, 2, -18, 0, 0, 0, 0, 0, 12};
// int[] a = {0, 0, 0, 0, 0};
// int[] a = {1, 2, 0, 0, 0, 0, 2, -18, 0, 0, 0, 0, 0, 12};
// int[] a = {0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0};
// int[] a = {1, 2, 3, 4};
// int[] a = {1, 0, 0, 0, 2, 0, 0, 0, 0};
// int[] a = {0};
int[] a = {};
System.out.println(isZeroPlentiful(a));
}
public static int isZeroPlentiful(int[] a){
if(a.length >= 4) {
int count = 0;
int zeroCount = 0;
for (int i = 0; i < a.length; i++) {
System.out.println("i="+i);
if (a[i] == 0) {
count++;
} else if (count >= 4) {
zeroCount++;
count = 0;
} else if (count > 0) {
return 0;
}
}
if(count >= 4){
zeroCount ++;
}
return zeroCount;
}else {
System.out.println("esle");
return 0;
}
}
}