题目:
解法一:
public int getLargestSeriesProduct(String input,int digits) {
// put numbers in int array
int [] numSet = new int [input.length()];
for (int i = 0; i < numSet.length; i++) {
numSet[i] = Character.getNumericValue(input.charAt(i));
}
// calculate the largest series product
int largestProduct = 0;
int sum = 1;
for (int i = 0; i < (numSet.length - digits); i++) {
for (int j = 0; j < digits; j++) {
if (numSet[i + j] == 0) {sum = 0;break;}
sum *= numSet[i + j];
}
if (sum > largestProduct) {largestProduct = sum;}
sum = 1;
}
return largestProduct;
}
解法二:
import io.vavr.collection.Stream;
import io.vavr.collection.Traversable;
import java.util.regex.Pattern;
public class LargestSeriesProductCalculator {
private final String numbers;
public LargestSeriesProductCalculator(String numbers) {
if (numbers == null) {
throw new IllegalArgumentException("String to search must be non-null.");
}
if (Pattern.compile("[^0-9]").matcher(numbers).find()) {
throw new IllegalArgumentException("String to search may only contains digits.");
}
this.numbers = numbers;
}
public long calculateLargestProductForSeriesLength(int window) {
if (window < 0) {
throw new IllegalArgumentException("Series length must be non-negative.");
}
if (window == 0) {
return 1;
}
if (window > numbers.length()) {
throw new IllegalArgumentException("Series length must be less than or equal to the length of the string to search.");
}
return Stream.ofAll(numbers.toCharArray())
.map(Character::getNumericValue)
.sliding(window)
.map(Traversable::product)
.max()
.getOrElseThrow(() -> new ArithmeticException("No maximum found in sequence"))
.longValue();
}
}