Golang 程序关闭数字中的第 k 位。
示例
Consider n = 20(00010100), k = 3 The result after turning off the 3rd bit => 00010000 & ^(1<<(3-1)) => 00010000 & ^(1 << 2) => 00010000 => 16s
解决这个问题的方法
Step1-定义一个方法,其中n和k是参数,返回类型是int。
步骤2-使用n&^(1<<(k-1))执行AND运算。
步骤3-返回获得的数字。
示例
package main import ( "fmt" "strconv" ) func TurnOffKthBit(n, k int) int { return n & ^(1 << (k-1)) } func main(){ var n = 20 var k = 3 fmt.Printf("Binary of %d is: %s.\n", n, strconv.FormatInt(int64(n), 2)) newNumber := TurnOffKthBit(n, k) fmt.Printf("After turning off %d rd 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 off 3 rd bit of 20 is 16. Binary of 16 is: 10000.