1356. 根据数字二进制下 1 的数目排序 增加go语言的解法

1356. 根据数字二进制下 1 的数目排序 增加go语言的解法
This commit is contained in:
SwaggyP
2022-09-04 10:21:43 +08:00
committed by GitHub
parent a605d75ec6
commit d0d693ffae

View File

@ -170,6 +170,39 @@ class Solution:
## 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