We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent a605d75 commit d0d693fCopy full SHA for d0d693f
problems/1356.根据数字二进制下1的数目排序.md
@@ -170,6 +170,39 @@ class Solution:
170
## Go
171
172
```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
206
```
207
208
## JavaScript
0 commit comments