Golang 程序切换给定数字 n 中的第 K 位。
示例
考虑n = 20(00010100),k = 3。
在切换给定数字的第 k 位后:00010000 => 16。
解决此问题的办法
步骤 1 − 定义一个方法,其中 n 和 k 为参数,返回类型为 int。
步骤 2 − 使用 n ^ (1<<(k-1)) 执行 AND 运算。
步骤 3 − 返回运算后的数字。
示例
package main
import (
"fmt"
"strconv"
)
func ToggleKthBit(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))
number := ToggleKthBit(n, k)
fmt.Printf("After toggling %d rd bit of the given number is %d.\n", k, number)
}输出
Binary of 20 is: 10100. After toggling 3 rd bit of the given number is 16.
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP