less than 1 minute read

[Lesson1] Iterations

BinaryGap : Find longest sequence of zeros in binary representation of an integer.


Java Solution

import java.util.*;

class Solution {
    public int solution(int N) {
        // 10진수 -> 2진수
        ArrayList<Integer> binary = new ArrayList<Integer>();
        while(0 < N){
            binary.add(N%2);
            N = N/2;
        }
        int count = 0;
        int max = 0;
        boolean start = false;
        // 1을 기준으로 다음 1이 나올때까지 숫자 count하여 max 값 구하기
        for(int i = 0; i < binary.size(); i++){
            if(binary.get(i) == 1){
                start = true;
            }
            if(start){
              if(binary.get(i) == 0){
                count++;
              }else{
                    if(count > max){
                        max = count;
                    }
                    count = 0;
                }
            }
        }
        return max;
    }
}

PHP Solution

function solution($N) {
    $binary = array();
    $i = 0;
    while(0 < $N){
        $binary[$i] = $N%2;
        //echo $binary[$i],"\n";
        $N = (int)$N/2;
        $i++;
    }
    $count = 0;
    $max = 0;
    $start = false;
    for($i = 0; $i < count($binary); $i++){
        if($binary[$i] == 1){
            $start = true;    
        }
        if($start){
            if($binary[$i] == 0){
                $count++;    
            }else{
                if($count > $max){
                    $max = $count;
                }
                $count = 0;
            }
        }
    }
    return $max;
}