IT 개발자_S

[코딜리티] Binary Gap 본문

IT/알고리즘_JAVA

[코딜리티] Binary Gap

Soso12 2020. 5. 9. 15:03
반응형

1. 입력값 N 입력후 Binary 값으로 변환

2. Binary 값으로 변환하기 위해 Integer 클래스의 toBinaryString 메소드 활용

3. binaryChar 배열 형태로 각각 정보를 입력받은 후

4. 배열의 값이 1인 경우 전 후 값을 비교하여 Binary Gap 값을 찾는다

 

// you can also use imports, for example:
import java.util.*;

// you can write to stdout for debugging purposes, e.g.
// System.out.println("this is a debug message");

class Solution {
    public int solution(int N) {
        // write your code in Java SE 8
        String binaryString = Integer.toBinaryString(N);
        
        char[] binaryChar = binaryString.toCharArray();
        
        int temp_result =0;
        int result =0;
        int bFcheck = -1;
        int aFcehck = -1;
        // 1 0 0 0 0 0 1 0 0 0 1

        
        for (int i =0; i <binaryChar.length; i++ ){
            if(binaryChar[i] =='1' && bFcheck ==-1 ){

                bFcheck = i;

            }else if(binaryChar[i] =='1' ){
     
                aFcehck = i;
                temp_result = aFcehck -bFcheck -1;
                if(result < temp_result) {
                    result = temp_result ;
                } 
                bFcheck = i;
            }
            
            
        }

        
        
        return result;
            
        
    }
}
반응형

'IT > 알고리즘_JAVA' 카테고리의 다른 글

[코딜리티] TapeEquilibrium  (0) 2020.05.10
[코딜리티]PermMissingElem  (0) 2020.05.10
[코딜리티]Frog_jump  (0) 2020.05.10
[코딜리티]OddOccurrencesInArray  (0) 2020.05.09
[코딜리티]CyclicRotation  (0) 2020.05.09
Comments