cubegao

Swift.二进制中1的个数

2015-07-05

题目描述:输入一个整数,输出该数二进制表示中 1 的个数。

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
class For10Solution {
func findOne(_ n: Int) -> Int {
var s = n
var count = 0

while s != 0 {
if s & 1 == 1 {
count += 1
}

s = s>>1
}

return count
}

func findOne2(_ n: Int) -> Int {
var s = n
var count = 0

while s != 0 {
count += 1
s = s & (s - 1)
}

return count
}
}

算法思想:n&(n-1),该位运算去除 n 的位级表示中最低的那一位。

github地址:https://github.com/cubegao/LeetCode

Tags: 算法

扫描二维码,分享此文章