본문 바로가기

LeetCode

868. Binary Gap / TypeScript

Given a positive integer n, find and return the longest distance between any two adjacent 1's in the binary representation of n. If there are no two adjacent 1's, return 0.

Two 1's are adjacent if there are only 0's separating them (possibly no 0's). The distance between two 1's is the absolute difference between their bit positions. For example, the two 1's in "1001" have a distance of 3.

 

Example 1:

Input: n = 22
Output: 2
Explanation: 22 in binary is "10110".
The first adjacent pair of 1's is "10110" with a distance of 2.
The second adjacent pair of 1's is "10110" with a distance of 1.
The answer is the largest of these two distances, which is 2.
Note that "10110" is not a valid pair since there is a 1 separating the two 1's underlined.

Example 2:

Input: n = 8
Output: 0
Explanation: 8 in binary is "1000".
There are not any adjacent pairs of 1's in the binary representation of 8, so we return 0.

Example 3:

Input: n = 5
Output: 2
Explanation: 5 in binary is "101".

 

출처: https://leetcode.com/problems/binary-gap/description/

 

 

function binaryGap(n: number): number {
    const binary = n.toString(2);
    let max = 0;
    let count;
    for(let i = 0; i < binary.length; i++){
        if(binary[i]==='1'){
            if(count !== undefined){
                if(i-count > max) max = i - count;
                count = i;
            }else {
                count = i;
            }
        }
    }
    return max;
};

 

ex) n = 22

22 -> "10110"

 

첫 번째 '1'을 찾았을 때 (i = 0):

if(count !== undefined){
    // 이 부분은 실행되지 않음
} else {
    count = i; // count = 0
}

 

두 번째 '1'을 찾았을 때 (i = 2):

if(count !== undefined){
    if(i - count > max) max = i - count; // i - count = 2 - 0 = 2, max = 2
    count = i; // count = 2
} else {
    // 이 부분은 실행되지 않음
}

 

세 번째 '1'을 찾았을 때 (i = 3):

if(count !== undefined){
    if(i - count > max) max = i - count; // i - count = 3 - 2 = 1, max는 이미 2이므로 변화 없음
    count = i; // count = 3
} else {
    // 이 부분은 실행되지 않음
}

 

 

 

  • 숫자 22를 이진수로 변환하면 "10110"
  • 이진 문자열에서 '1'의 위치는 0, 2, 3
  • '1'과 '1' 사이의 최대 간격은 2
  • binaryGap(22) 함수는 2를 반환