Golang 程序寻找最右边设置位的位置
示例
假设 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", 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.
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP