题倒是很简单,最开始用了这么一种解法:
package main
import "fmt"
func main() {
a := 0
fmt.Scan(&a)
str := fmt.Sprintf("%b", a)
fmt.Printf("%d", convert(str))
}
func convert(str string) int {
sum := 0
for i := 0; i < len(str); i++ {
if str[i] == '1' {
sum += 1
}
}
return sum
}
但是看着就不是很优雅,还是用位运算看着优雅些:
package main
import "fmt"
func main() {
a := 0
fmt.Scan(&a)
count := 0
for a != 0 {
if a&1 == 1 {
count += 1
}
a = a >> 1
}
fmt.Printf("%d", count)
}
标签:count,HJ15,func,int,fmt,牛客,str,main
From: https://www.cnblogs.com/wingsless/p/17122166.html