코딩 테스트/LeetCode(swift)

[LeetCode] 191. Number of 1 Bits

Skillist 2021. 4. 6. 21:51
반응형

문제

leetcode.com/problems/number-of-1-bits/

 

Number of 1 Bits - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

잠깐만

비트 연산으로 풀어보세요

 

코드

class Solution {
    func hammingWeight(_ n: Int) -> Int {
        var targetNum = n
        var count = 0
        for i in 0..<32 {
            count += (targetNum & 1)
            targetNum = targetNum >> 1
        }
        return count
    }
}

 

설명

비트 연산을 통해, 1의 개수를 계산했습니다.

반응형