問題
コード1
- 2進数に変換(Integer#toBinaryString)
- 文字列を char型の配列に変換( String#toCharArray)
public int solution(int N) {
char[] chars = Integer.toBinaryString(N).toCharArray();
int gap = 0;
int count = 0;
for (char num : chars) {
if (num == '0') {
count++;
} else {
if (count > gap) {
gap = count;
}
count = 0;
}
}
return gap;
}
コード2
public int solution(int N) {
String[] strings = Integer.toBinaryString(N)
.replaceAll("0+$", "")
.split("1");
int gap = 0;
for (String str : strings) {
int count = str.length();
if (count > gap) {
gap = count;
}
}
return gap;
}
コード3
public int solution(int N) {
return Stream.of(Integer.toBinaryString(N)
.replaceAll("0+$", "")
.split("1"))
.max((e1, e2) -> Integer.compare(e1.length(), e2.length()))
.map(e -> e.length())
.orElse(0);
}