Golang 程序打开数字中的第 k 位。
示例
For example consider n = 20(00010100), k = 4. So result after turning on 4th bit => 00010000 | (1 << (4-1))
解决这个问题的方法
Step1-定义一个方法,其中n和k将是参数,返回类型为int。
步骤2-使用n|执行AND运算(1<<(k-1))。
步骤3-返回获得的数字。
示例
package main import ( "fmt" "strconv" ) func TurnOnKthBit(n, k int) int { return n | (1 << (k-1)) } func main(){ var n = 20 var k = 4 fmt.Printf("Binary of %d is: %s.\n", n, strconv.FormatInt(int64(n), 2)) newNumber := TurnOnKthBit(n, k) fmt.Printf("After turning on %d th bit of %d is: %d.\n", k, n, newNumber) fmt.Printf("Binary of %d is: %s.\n", newNumber, strconv.FormatInt(int64(newNumber), 2)) }输出结果
Binary of 20 is: 10100. After turning on 4 th bit of 20 is: 28. Binary of 28 is: 11100.