Golang程序查找最右边的设置位的位置
例子
考虑n=20(00010100)
现在返回日志2(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", n, strconv.FormatInt(int64(n), 2))
fmt.Printf("Position of the rightmost set bit of the given number %d is %d.\n", n, FindRightMostSetBit(n))
}输出结果Binary of 20 is: 10100. Position of the rightmost set bit of the given number 20 is 3.
热门推荐
10 新人红包祝福语简短精辟
11 幼师给毕业祝福语简短
12 生日高考祝福语妹妹简短
13 下飞机祝福语简短英文
14 元宵发客户祝福语简短
15 爸妈金婚文案祝福语简短
16 新郎朋友红包祝福语简短
17 虎年五一祝福语大全简短
18 出阁宴祝福语姐姐简短