A binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of N.
For example, number 9 has binary representation 1001 and contains a binary gap of length 2. The number 529 has binary representation 1000010001 and contains two binary gaps: one of length 4 and one of length 3. The number 20 has binary representation 10100 and contains one binary gap of length 1. The number 15 has binary representation 1111 and has no binary gaps. The number 32 has binary representation 100000 and has no binary gaps.
Write a function:
class Solution { public int solution(int N); }
that, given a positive integer N, returns the length of its longest binary gap. The function should return 0 if N doesn't contain a binary gap.
For example, given N = 1041 the function should return 5, because N has binary representation 10000010001 and so its longest binary gap is of length 5. Given N = 32 the function should return 0, because N has binary representation '100000' and thus no binary gaps.
Write an efficient algorithm for the following assumptions:
- N is an integer within the range [1..2,147,483,647]
class Solution {
public int solution(int N) {
String binary_s = Integer.toBinaryString(N);
int startIdx = binary_s.indexOf("1");
int endIdx = binary_s.lastIndexOf("1");
int answerMax = 0;
int answer = 0;
for(int i = startIdx; i<=endIdx; i++){
if(binary_s.charAt(i) == '0'){
answer = answer +1;
}
else {
answerMax = Math.max(answer, answerMax);
answer = 0;
}
}
return answerMax;
}
}
String 클래스
.indexOf()
.lastIndexOf()
.charAt()
String string = "appleappleapple";
// .indexOf() : p가 있는 index를 앞에서부터 찾아서 반환
string.indexOf('p'); // 결과 : 1
// .lastIndexOf() : p가 있는 index를 뒤에서부터 찾아서 반환
string.lastIndexOf('p'); // 결과 : 12
// .charAt() : 4 index에 있는 문자 반환
string.charAt(4); // 결과 : e
Integer 클래스
Integer.toBinaryString()
// .toBinaryString() : 10진수 int형을 2진수 string으로 변환
String string = Integer.toBinaryString(534); // 결과 : "1000010110"
출처
'Language > Java' 카테고리의 다른 글
Java 컬렉션(Collection) (0) | 2021.04.22 |
---|---|
Java 자료형 (0) | 2021.04.22 |
POJO, DAO, DTO, VO 차이 (0) | 2021.04.22 |
메모리 누수 (Memory leak) (0) | 2021.04.20 |
자바 가상머신 (JVM: Java Virtual Machine) (0) | 2021.04.20 |