英文:
is power of 2 with golang
问题
我想检查给定的数字是否是2的幂。我已经写了一段代码,但是无法返回true或false,我觉得可能有一个无限循环的地方。我只能在代码中使用导入包的函数。我无法弄清楚如何纠正错误。如果你能帮助我,我会很高兴的
package main
import (
"os"
"strconv"
)
func main() {
for len(os.Args) == 2 {
numbers, err := strconv.Atoi(os.Args[1])
if err != nil {
panic(err)
}
newnum := numbers
counts := 0
for numbers != 1 {
if newnum%2 != 0 {
} else {
newnum = newnum / 2
}
counts++
}
var x int = 2 ^ counts
if x == numbers {
return true
} else {
return false
}
}
}
请注意,你的代码中有一些问题。首先,你不能在main
函数中使用return
语句,因为main
函数的返回类型是void
。其次,你使用的是异或运算符^
,而不是求幂运算符**
。你可以尝试修改代码如下:
package main
import (
"fmt"
"os"
"strconv"
)
func main() {
if len(os.Args) == 2 {
numbers, err := strconv.Atoi(os.Args[1])
if err != nil {
panic(err)
}
newnum := numbers
counts := 0
for newnum%2 == 0 && newnum != 0 {
newnum = newnum / 2
counts++
}
result := numbers == 1<<counts
fmt.Println(result)
}
}
这个修改后的代码将打印出给定数字是否是2的幂。如果是,将打印true
,否则打印false
。希望对你有帮助!
英文:
I want to check whether the number given is a power of 2. I have written a code but I cannot return true or false, I think somewhere there is an infinite loop. I am only allowed to use functions from imported packages on the code. I could not figure out what to do to correct the mistake. I would be glad if you can help me
>
package main
import (
"os"
"strconv"
)
func main() {
for len(os.Args) == 2 {
numbers, err := strconv.Atoi(os.Args[1])
if err != nil {
panic(err)
}
newnum := numbers
counts := 0
for numbers != 1 {
if newnum%2 != 0 {
} else {
newnum = newnum / 2
}
counts++
}
var x int = 2 ^ counts
if x == numbers {
return true
} else {
return false
}
}
}
`
答案1
得分: 5
根据@phuclv的评论,我已经根据您的情况创建了一个示例程序,使用n & (n - 1) == 0
,代码如下:
//假设 n = 16(00010000)
//现在找到 x = n-1 => 15(00001111) => x & n => 0
func CheckPowerOfTwo(n int) int {
//添加一个特殊情况,如果 n 为零,也将被视为2的幂
if n==0{
return 1
}
return n & (n - 1)
}
func main() {
var n = 16
flag := CheckPowerOfTwo(n)
if flag == 0 {
fmt.Printf("给定的 %d 数字是2的幂。\n", n)
} else {
fmt.Printf("给定的 %d 数字不是2的幂。\n", n)
}
}
您可以在此处运行它:https://go.dev/play/p/9cRWwiFAIn8
英文:
As commented by @phuclv , I have created a sample program for your scenario by using n & (n - 1) == 0
as follows :
//Let's assume n = 16(00010000)
//Now find x = n-1 => 15(00001111) => x & n => 0
func CheckPowerOfTwo(n int) int {
//added one corner case if n is zero it will also consider as power 2
if n==0{
return 1
}
return n & (n - 1)
}
func main() {
var n = 16
flag := CheckPowerOfTwo(n)
if flag == 0 {
fmt.Printf("Given %d number is the power of 2.\n", n)
} else {
fmt.Printf("Given %d number is not the power of 2.\n", n)
}
}
You can run it here : https://go.dev/play/p/9cRWwiFAIn8
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论