exercism ————LargestSeriesProduct

题目:

在这里插入图片描述

解法一:

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();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值