Golang 程式用於開啟數字中的第 k 位。
示例
For example consider n = 20(00010100), k = 4. So result after turning on 4th bit => 00010000 | (1 << (4-1))
解決此問題的方法
步驟 1 − 定義一個方法,其中n和k是引數,返回型別是int。
步驟 2 − 對n | (1<<(k-1)) 執行 AND 運算。
步驟 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.
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP