Codility_BinaryGap

functionMan·2024년 8월 1일

Codility

목록 보기
1/32
post-thumbnail
  1. BinaryGap
    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.

받은 수를 이진법으로 변환하고 변환된 이진수의 1과 1사이의 0의 갯수가 가장 많은 것을 출력하라는 문제였다.

문제풀이

import java.util.*;

class Solution {
    public int solution(int N) {
        // int N을 toBinaryString을 통해 2진수의 문자열로 변환
        String binary = Integer.toBinaryString(N);
        // 변환된 문자열을 배열화 함
        String[] binaryArr = binary.split("");
        // 0의 갯수를 체크하기 위해 작성
        int zeroCount = 0;
        // 1과 1사이에 0이 들어있는 다른 경우도 있음으로 큰 수를 저장하기 위해 작성 
        int zeroMaxCount = 0;
        // 1일 경우 카운팅을 시작하기 위해 작성
        boolean counting = false;

		// binaryArr만큼 반복을 위해 for 문을 사용함
        for(String s : binaryArr){
        		// 1일 경우 카운팅을 true로 활성화 하고 zeroMaxCount를 변경
                if(s.equals("1")){
                    if(counting){
                        if(zeroCount > zeroMaxCount){
                            zeroMaxCount = zeroCount;
                        }
                        zeroCount = 0;
                    }
                    counting = true;
                 // 0이고 카운팅 상태일 경우 zeroCount를 카운팅
                }else if(s.equals("0") && counting){
                    zeroCount++;
                }
                
        }
        // zeroMaxCount가 0인 경우에는 0을 반환
        if(zeroMaxCount == 0){
            return 0;
        // 0이 아닌 경우에는 최대 카운팅된 결과를 반환
        }else{
            return zeroMaxCount;
        }
    }
}

문제 제출결과

문제 풀어보기 ->
https://app.codility.com/programmers/lessons/1-iterations/binary_gap/

profile
functionMan

0개의 댓글