当前位置: 代码迷 >> 综合 >> exercism ————LargestSeriesProduct
  详细解决方案

exercism ————LargestSeriesProduct

热度:95   发布时间:2023-12-13 18:10:30.0

题目:

在这里插入图片描述

解法一:

public int getLargestSeriesProduct(String input,int digits) {
    // put numbers in int arrayint [] numSet = new int [input.length()];for (int i = 0; i < numSet.length; i++) {
    numSet[i] = Character.getNumericValue(input.charAt(i));}// calculate the largest series productint 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();}
}