mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
1356. 根据数字二进制下 1 的数目排序 增加go语言的解法
1356. 根据数字二进制下 1 的数目排序 增加go语言的解法
This commit is contained in:
@ -170,6 +170,39 @@ class Solution:
|
|||||||
## Go
|
## Go
|
||||||
|
|
||||||
```go
|
```go
|
||||||
|
func sortByBits(arr []int) []int {
|
||||||
|
var tmp int
|
||||||
|
for i := 0; i < len(arr); i++ {
|
||||||
|
for j := i+1; j < len(arr); j++ {
|
||||||
|
// 冒泡排序的手法,但是排序的规则从比大小变成了比位运算1的个数
|
||||||
|
if isCmp(arr[i], arr[j]) {
|
||||||
|
tmp = arr[i]
|
||||||
|
arr[i] = arr[j]
|
||||||
|
arr[j] = tmp
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return arr
|
||||||
|
}
|
||||||
|
|
||||||
|
func isCmp(a, b int) bool {
|
||||||
|
bitA := bitCount(a)
|
||||||
|
bitB := bitCount(b)
|
||||||
|
if bitA == bitB {
|
||||||
|
return a > b
|
||||||
|
} else {
|
||||||
|
return bitA > bitB
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func bitCount(n int) int {
|
||||||
|
count := 0
|
||||||
|
for n != 0 {
|
||||||
|
n &= (n-1) // 清除最低位的1
|
||||||
|
count++
|
||||||
|
}
|
||||||
|
return count
|
||||||
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
## JavaScript
|
## JavaScript
|
||||||
|
Reference in New Issue
Block a user