Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 021dfb2

Browse files
committedApr 15, 2025·
Solution number of 1 bits
1 parent 9540c6c commit 021dfb2

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed
 

‎number-of-1-bits/HISEHOONAN.swift

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
//
2+
// Untitled.swift
3+
// Algorithm
4+
//
5+
// Created by 안세훈 on 4/14/25.
6+
//
7+
8+
class Solution {
9+
func hammingWeight(_ n: Int) -> Int {
10+
var num = n //n을 저장할 변수
11+
var remain = 0 //나머지를 저장할 변수
12+
var array : [Int] = [] //이진법으로 변환한 수를 저장할 배열
13+
14+
while num > 0{ //num이 0보다 클때만 반복
15+
remain = num % 2 //num을 2로 나눈 나머지를 저장
16+
num = num / 2 //num을 2로 나눈 몫을 저장
17+
array.append(remain) //array에 나머지를 저장
18+
}
19+
20+
return array.filter{$0 == 1}.count //array에 1만 추출한 후 그 개수 리턴
21+
}
22+
}

0 commit comments

Comments
 (0)
Please sign in to comment.