好的,这是IntStream的一个有趣的实现:
public static int reverse (int n) {
return IntStream.iterate (n, i -> i/10) // produces a infinite IntStream of n, n/10,
// n/100, ...
.limit(10) // 10 elements are sufficient, since int has <= 10 digits
.filter (i -> i > 0) // remove any trailing 0 elements
.map(i -> i % 10) // produce an IntStream of the digits in reversed
// order
.reduce (0, (r,i) -> r*10 + i); // reduce the reversed digits back
// to an int
}
例如,对于输入123456789,它将首先生成无限IntStream:
123456789,12345678,1234567,123456,12345,1234,123,12,1,0,0,...
限制为10个元素并删除0后,我们留下:
123456789,12345678,1234567,123456,12345,1234,123,12,1
将每个元素映射到最后一个数字后,我们得到:
9,8,7,6,5,4,3,2,1
现在我们只需要以类似于您在问题中所做的方式减少IntStream – 将每个元素添加到中间结果乘以10:
((((0 * 10 + 9) * 10 + 8) * 10 + 7) * 10 ....) * 10 + 1
请注意,如果输入的数字有10位数字,则最后一位数字> 1,反转结果会溢出.
它也不支持负面输入.