티스토리 뷰

Coding

c0dility. 1. BinaryGap

out of coding 2019. 11. 23. 13:41

처음하는거라 어리둥절.

웬지 코딩 문제들은 현업에서는 안할거 같은 코드를 만드는 듯.

 

Solution

public func solution(_ N : Int) -> Int {
    var number = N
    var maxValue = 0
    var sum = 0
    var firstCheck = false

    while number != 0 {
        let digit = number % 2
        number = number / 2
        
        if digit == 1 && !firstCheck {
            firstCheck = true
        }
        
        guard firstCheck else { continue }
        
        if digit == 1 {
            maxValue = max(sum, maxValue)        
            sum = 0    
        } else {
            sum += 1
        }
    }
    
    return maxValue
}

https://app.codility.com/demo/results/training6WT9YX-Y3N/

 

Test results - Codility

A binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of N. For example, number 9 has binary representation 1001 and contains a binary gap of length 2. The

app.codility.com

 

'Coding' 카테고리의 다른 글

배열에서 가장 큰 정사각형 찾기  (0) 2019.12.02
fibonacci. index에 해당하는 값은?  (0) 2019.11.27
Stack을 이용하여 Queue 만들기  (0) 2019.11.21
ROT13  (0) 2019.08.14
Algorithm. swift. 진수 변환  (0) 2018.07.16
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/05   »
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
글 보관함