[英]Recursive Sum of digits of number(until digit is less than 10) java 8 lambdas only
I am just practicing lamdas java 8. My problem is as follows 我只是练习lamdas java 8.我的问题如下
Sum all the digits in an integer until its less than 10(means single digit left) and checks if its 1 将一个整数中的所有数字求和,直到小于10(表示剩下一位数)并检查其是否为1
Sample Input 1 样本输入1
100
Sample Output 1 样本输出1
1 // true because its one
Sample Input 2 样本输入2
55
Sample Output 2 样本输出2
1 ie 5+5 = 10 then 1+0 = 1 so true
I wrote a code 我写了一个代码
System.out.println(Arrays.asList( String.valueOf(number).split("") ).stream()
.map(Integer::valueOf)
.mapToInt(i->i)
.sum() == 1);
It works for the input 1 ie 100 but not for input 2 ie 55 which I clearly understand that in second case 10 is the output because the iteration is not recursive . 它适用于输入1即100但不适用于输入2,即55,我清楚地理解,在第二种情况下10是输出,因为迭代不是递归的。
So how can I make this lambdas expression recursive so that it can work in second case also? 那么如何才能使这个lambdas表达式递归,以便它也可以在第二种情况下工作呢? I can create a method with that lambda expression and call it each time until return value is< 10 but I was thinking if there is any approach within lambdas. 我可以使用该lambda表达式创建一个方法并每次调用它,直到返回值<10,但我在想是否在lambdas中有任何方法。
Thanks 谢谢
If you want a pure lambda solution, you should forget about making it recursive, as there is absolutely no reason to implement an iterative process as a recursion: 如果你想要一个纯lambda解决方案,你应该忘记使它递归,因为绝对没有理由将迭代过程实现为递归:
Stream.iterate(String.valueOf(number),
n -> String.valueOf(n.codePoints().map(Character::getNumericValue).sum()))
.filter(s -> s.length()==1)
.findFirst().ifPresent(System.out::println);
Making lambdas recursive in Java is not easy because of the "variable may be uninitialized" error, but it can be done. 在Java中使lambdas递归并不容易,因为“变量可能是未初始化的”错误,但它可以完成。 Here is a link to an answer describing one way of doing it . 这是一个回答的链接,描述了一种方法 。
When applied to your task, this can be done as follows: 应用于您的任务时,可以按如下方式完成:
// This comes from the answer linked above
class Recursive<I> {
public I func;
}
public static void main (String[] args) throws java.lang.Exception {
Recursive<Function<Integer,Integer>> sumDigits = new Recursive<>();
sumDigits.func = (Integer number) -> {
int s = Arrays.asList( String.valueOf(number).split("") )
.stream()
.map(Integer::valueOf)
.mapToInt(i->i)
.sum();
return s < 10 ? s : sumDigits.func.apply(s);
};
System.out.println(sumDigits.func.apply(100) == 1);
System.out.println(sumDigits.func.apply(101) == 1);
System.out.println(sumDigits.func.apply(55) == 1);
System.out.println(sumDigits.func.apply(56) == 1);
}
I took your code, wrapped it in {
... }
s, and added a recursive invocation on the return
line. 我把你的代码包装在{
... }
,并在return
行上添加了一个递归调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.