본문 바로가기

코딩 테스트/LeetCode(swift)

[LeetCode] 191. Number of 1 Bits

반응형

문제

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의 개수를 계산했습니다.

반응형

'코딩 테스트 > LeetCode(swift)' 카테고리의 다른 글

[LeetCode] 268. Missing Number  (0) 2021.04.07
[LeetCode] 338. Counting Bits  (0) 2021.04.06
[LeetCode] 371. Sum of Two Integers  (0) 2021.04.06
[LeetCode] 11. Container With Most Water  (0) 2021.03.24
[LeetCode] 15. 3Sum  (0) 2021.03.23