如何使用Java 8 Stream / Lambda计算整数中的尾随零数?

时间:2019-01-29 17:33:12

标签: algorithm java-8 java-stream

如何使用Java 8 Stream / Lambda计算整数中的尾随零数?

基本上,逻辑应该是:将整数除以cat("\nBaseDate: ", format(theDate, '%m/%d/%Y'), "\tMBP Date: ", FormatDate) BaseDate: 01/01/2019 MBP Date: 12/31/2018 BaseDate: 01/02/2019 MBP Date: 12/31/2018 BaseDate: 01/03/2019 MBP Date: 01/02/2019 BaseDate: 01/04/2019 MBP Date: 01/03/2019 BaseDate: 01/05/2019 MBP Date: 01/04/2019 BaseDate: 01/06/2019 MBP Date: 01/04/2019 ,只要余数为10(商将提供给下一个除法)并计算出现的次数。 / p>

例如

0 12300 % 10 == 0

true 1230 % 10 == 0

true 123 % 10 == 0

答案:false

注意::我不想在这里不涉及String:-)

3 个答案:

答案 0 :(得分:3)

如果这是一个纯粹的假设问题,那么这是一个关于如何执行的纯粹的假设答案:

static int countZeroes(int value) {
    if(value == 0) // we need to handle this case explicitly
        return 1; 
    IntStream s = IntStream.iterate(value, v -> v / 10);
    return (int) takeWhile(s, v -> v > 0 && v % 10 == 0)
            .count();

}

它使用Java 9中提供的助手功能takeWhile,但Java 8中没有,因此必须这样模拟:

// In Java 9 there is a standard takeWhile
// https://docs.oracle.com/javase/9/docs/api/java/util/stream/Stream.html#takeWhile-java.util.function.Predicate-
// but in Java 8 I have to emulate it
static IntStream takeWhile(IntStream s, final IntPredicate pr) {
    final Spliterator.OfInt origSp = s.spliterator();

    Spliterator.OfInt filtered = new Spliterators.AbstractIntSpliterator(origSp.estimateSize(), 0) {
        boolean lastPredicate = true;

        @Override
        public boolean tryAdvance(final IntConsumer action) {
            if (!lastPredicate)
                return false;

            origSp.tryAdvance((int v) -> {
                lastPredicate = pr.test(v);
                if (lastPredicate) {
                    action.accept(v);
                }
            });
            return lastPredicate;
        }
    };

    return StreamSupport.intStream(filtered, false);
}

这个想法是

IntStream.iterate(value, v1 -> v1 / 10).takeWhile(v -> v > 0)

应在结尾处一一生成剪切数字流,然后可以应用takeWhile(v -> v % 10 == 0).count()来计数零的数量,最后可以将这两个takeWhile合并为一。

答案 1 :(得分:1)

这是另一种方式:-

private static int countTrailingZeroes(int n) {
    int length = n == 0 ? 1 : (int) (Math.log10(n) + 1); //number of digits in n
    return IntStream.rangeClosed(0, length)
            .map(i -> length - i)           //reverse stream
            .map(o -> (int) Math.pow(10, o))
            .filter(o -> n % o == 0)
            .boxed()
            .findFirst()
            .map(i -> (int) Math.log10(i))  //number of digits minus 1
            .orElse(0);
}

@Holger的编辑:

private static int countTrailingZeroes(int n) {
    int length = n == 0 ? 1 : (int) (Math.log10(n) + 1); //number of digits in n
    return IntStream.rangeClosed(0, length)
            .map(i -> length - i)           //reverse stream
            .filter(o -> n % (int) Math.pow(10, o) == 0)
            .findFirst()
            .orElse(0);
}

答案 2 :(得分:1)

考虑到您没有Java9的{​​{1}}方法,这也可以解决问题:

takeWhile
相关问题