如何使用Java 8 Stream/Lambda计算整数中的尾随零数? [英] How to count the number of trailing zeroes in an integer using Java 8 Stream/Lambda?

查看:83
本文介绍了如何使用Java 8 Stream/Lambda计算整数中的尾随零数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How to count the number of trailing zeroes in an integer using Java 8 Stream/Lambda?

基本逻辑应为:只要整数除以10,只要余数为0(商将提供给下一个除法),然后计算出现的次数.

Basically the logic should be: keep the integer dividing by 10 as long as the remainder is 0 (the quotient will be supplied to the next division) and count the occurrence(s).

例如

12300 % 10 == 0 true

1230 % 10 == 0 true

123 % 10 == 0 false

答案:2

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

Note: I prefer not to involve String here :-)

推荐答案

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

If this is a purely hypothetical question, here is a purely hypothetical answer of how you can do it:

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中没有,因此必须这样模拟:

It uses a helper function takeWhile that is available in Java 9 but not in Java 8 so has to be emulated like this:

// 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合并为一个.

should generate a stream of cutting digits at the end one by one and then you can apply takeWhile(v -> v % 10 == 0).count() to count the number of zeros and finally you can merge those two takeWhiles into one.

这篇关于如何使用Java 8 Stream/Lambda计算整数中的尾随零数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆