【发布时间】:2019-11-28 21:18:48
【问题描述】:
作为学习 Java 8+ Streams 的练习,我想将一些简单的 Codility 实现转换为 Stream 解决方案。
例如,BinaryGap 问题.. 使用 Streams 的简单单线解决方案可能类似于:
public static int solution(int N) {
return Integer.toBinaryString(N).chars().
filter(x -> x == '1').whichIndexes().diff().max();
}
唯一的问题是,whichIndexes 和 diff 不存在。我需要一种方法来获取过滤元素的索引,然后计算它们的成对差异,这对于基于 Streams 的单线解决方案来说是一个很好的起点。
更新:这是我在 C++ 中的 BinaryGap 解决方案,但 Java 非 Stream-ed 版本会非常相似:
#include <bitset>
#include <iostream>
#include <math.h>
using namespace std;
int solution(int N) {
bitset<32> bs(N);
int maxGap = 0;
std::size_t i = 0;
while (bs[i] == 0) {
i++;
}
int startPos = i;
for (; i < bs.size(); ++i) {
if (bs[i] == 1) {
int gap = i - startPos - 1;
if (gap > maxGap) {
maxGap = gap;
}
startPos = i;
}
}
return maxGap;
}
int main() {
cout << solution(9) << " must be 2" << endl;
cout << solution(529) << " must be 4" << endl;
cout << solution(20) << " must be 1" << endl;
cout << solution(32) << " must be 0" << endl;
cout << solution(1041) << " must be 5" << endl;
return 0;
}
【问题讨论】:
-
关于已经有答案:嗯,但与this post 一起,它或多或少地被覆盖了。
标签: java algorithm java-stream