将数字中的第 k 位关掉


范例

Consider n = 20(00010100), k = 3
The result after turning off the 3rd bit => 00010000 & ^(1<<(3-1)) => 00010000 & ^(1 << 2) =>
00010000 => 16s

解决此问题的办法

步骤 1 − 定义一个方法,其中 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.

更新于: 17-Mar-2021

133 次浏览

开启你的 职业生涯

完成课程以获取认证

开始
广告
© . All rights reserved.