Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit d0d693f

Browse files
1356. 根据数字二进制下 1 的数目排序 增加go语言的解法
1356. 根据数字二进制下 1 的数目排序 增加go语言的解法
1 parent a605d75 commit d0d693f

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

‎problems/1356.根据数字二进制下1的数目排序.md‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -170,6 +170,39 @@ class Solution:
170170
## Go
171171

172172
```go
173+
func sortByBits(arr []int) []int {
174+
var tmp int
175+
for i := 0; i < len(arr); i++ {
176+
for j := i+1; j < len(arr); j++ {
177+
// 冒泡排序的手法,但是排序的规则从比大小变成了比位运算1的个数
178+
if isCmp(arr[i], arr[j]) {
179+
tmp = arr[i]
180+
arr[i] = arr[j]
181+
arr[j] = tmp
182+
}
183+
}
184+
}
185+
return arr
186+
}
187+
188+
func isCmp(a, b int) bool {
189+
bitA := bitCount(a)
190+
bitB := bitCount(b)
191+
if bitA == bitB {
192+
return a > b
193+
} else {
194+
return bitA > bitB
195+
}
196+
}
197+
198+
func bitCount(n int) int {
199+
count := 0
200+
for n != 0 {
201+
n &= (n-1) // 清除最低位的1
202+
count++
203+
}
204+
return count
205+
}
173206
```
174207

175208
## JavaScript

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /