티스토리 뷰

Codility-Lesson01. BinaryGap



문제

  • 랜덤으로 발생하는 10진수 숫자 N 을 int Type으로 받는다
  • 2진법으로 N 을 변환한다
    1. 2진법으로 표현된 N 에서 1과 1 사이에서 연속된 0의 최대 갯수를 리턴한다. 예컨대 2진법으로 변환한 결과가 ‘1010001’ 이라면 1과 1사이에 있는 0은 각각 1개, 3개 이다. 이중 최대값인 3을 리턴하면 된다. ‘100001001’ 의 경우에는 4 가 된다. 단 ‘10010000’ 인 경우 리턴 값은 2이다. 1과 1사이의 0 갯수만 해당되기 때문이다.


      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      34
      35
      36
      37
      38
      39
      40
      41
      42
      43
      44
      // 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");

      import java.util.ArrayList;
      class Solution {
          public int solution(int N) {
              // write your code in Java SE 8
              ArrayList<Integer> array = new ArrayList<Integer>();
              
              int count = 0;
              int max = 0;
              boolean flag = false;
              
              while(N > 0){
               array.add(N%2);
               N=N/2;   
              }
              
               for(int i = array.size()-1; i>=0; i--){
                
                if(array.get(i) == 1){
                 
                  if(flag){
                  
                      if(max < count){
                       max = count;
                       }
                      count=0;
                  }
                  else// 1 appers
                      count =0;
                      flag =true;
                  }
                }
                else{
                 count++;   
                }
               } 
                
               return max;
          }
      }
      cs



      '프로그래밍 > 알고리즘' 카테고리의 다른 글

      Codility-Lesson02-2. CyclicRotation  (0) 2017.10.18
      Codility-Lesson02-1. OddOccurrencessInArray  (0) 2017.10.18
      2 * N 타일링  (0) 2017.05.19
      [백준 7576번]토마토문제 풀기  (2) 2017.05.19
      탐욕 알고리즘  (0) 2017.03.24
      공지사항
      최근에 올라온 글
      최근에 달린 댓글
      Total
      Today
      Yesterday
      TAG
      more
      «   2024/07   »
      1 2 3 4 5 6
      7 8 9 10 11 12 13
      14 15 16 17 18 19 20
      21 22 23 24 25 26 27
      28 29 30 31
      글 보관함