示例考虑 n = 20(00010100)现在返回 log2(20 & -20) => 2+1 => 3解决此问题的方法步骤 1 - 定义一个方法,其中 n 是参数,返回类型为 int。步骤 2 - 返回 log2(n & -n)+1。示例package main import ( "fmt" "math" "strconv" ) func FindRightMostSetBit(n int) int { if (n & 1) != 0{ return 1 } return int(math.Log2(float64(n & -n))) + 1 } func main(){ var n = 20 fmt.Printf("Binary of %d is: %s.", n, strconv.FormatInt(int64(n), 2)) fmt.Printf("Position of the rightmost set bit of the given number %d is %d.", n, FindRightMostSetBit(n)) }输出Binary of 20 is: 10100. Position of the rightmost set bit of the given number 20 is 3.
示例考虑 n = 16(00010000)现在找到 x = n-1 => 15(00001111) => x & n => 0解决此问题的方法步骤 1 - 定义一个方法,其中 n 是参数,返回类型为 int。步骤 2 - 执行 x = n & n-1。步骤 3 - 如果 x 为 0,则给定数字为 2 的幂;否则不是。示例 实时演示package main import ( "fmt" "strconv" ) func CheckNumberPowerOfTwo(n int) int { return n & (n-1) } func main(){ var n = 16 fmt.Printf("Binary of %d is: %s.", n, strconv.FormatInt(int64(n), 2)) flag := CheckNumberPowerOfTwo(n) ... 阅读更多