알고리즘/해결

LeetCode868. Binary Gap

언클린 2020. 4. 12. 09:30
728x90

1. 문제(원본)

Given a positive integer N, find and return the longest distance between two consecutive 1's in the binary representation of N.

If there aren't two consecutive 1's, return 0.

 

 

Example 1:

Input: 22 Output: 2 Explanation: 22 in binary is 0b10110. In the binary representation of 22, there are three ones, and two consecutive pairs of 1's. The first consecutive pair of 1's have distance 2. The second consecutive pair of 1's have distance 1. The answer is the largest of these two distances, which is 2.

Example 2:

Input: 5 Output: 2 Explanation: 5 in binary is 0b101.

Example 3:

Input: 6 Output: 1 Explanation: 6 in binary is 0b110.

Example 4:

Input: 8 Output: 0 Explanation: 8 in binary is 0b1000. There aren't any consecutive pairs of 1's in the binary representation of 8, so we return 0.

 

Note:

  • 1 <= N <= 10^9

2. 문제

입력된 정수형 수의 이진수 중 1과 1의 간격이 가장 큰 수를 구하여라

3. 나의 답

class Solution {

    func binaryGap(_ N: Int) -> Int {

        var count = 0

        var moveCount = 0

        let binary = String(N, radix: 2)

        for element in binary {

            if element == "1" {

                count = max(moveCount, count)

                moveCount = 0

            }

            moveCount += 1

        }

        return count

    }

}

4. 다른 유저의 답

#1

class Solution {

    func binaryGap(_ N: Int) -> Int {

        let str = String(N, radix: 2) // to binary using 2

        var distance: Int = 0

        var last1: Int = 0

        for (i,bit) in str.enumerated() {

            if String(bit) == "1" {

                distance = max(distance, i - last1)

                last1 = i

            }

        }

        return distance

    }

}

5. 마무리

이번 문제에서는 다른 유저의 답과 비교해서 내 답변이 4ms 가장 빠르게 나타난 축에 속했다. 어느순간부터 문제를 그냥 풀기보다 어떻게 좀 더 효율적으로 풀수 있는지 메모리에 부담을 덜 수 있는지부터 생각하게 되는 것 같다. 

728x90

'알고리즘 > 해결' 카테고리의 다른 글

LeetCode226. Invert Binary Tree  (0) 2020.04.14
LeetCode412. Fizz Buzz  (0) 2020.04.12
LeetCode283. Move Zeroes  (0) 2020.04.12
LeetCode867. Transpose Matrix  (0) 2020.04.05
LeetCode1046. Last Stone Weight  (0) 2020.04.05