使用庫函式獲取給定數字所需總位數的Go語言程式


在這篇文章中,我們將討論如何使用Go語言的庫函式來獲取給定數字所需的總位數。

要獲得任何數字的總位數,我們需要將其轉換為二進位制表示(由零和一組成),然後計算零和一的個數。

例如:16可以轉換為二進位制10000,因此數字16的位數是5。

65可以轉換為二進位制1000001,因此數字65的位數是7。

語法

函式 -

func function_name([parameters]) [return_types]
{
   // Body of the function
}

for迴圈作為while迴圈 -

for condition {
   // code to be executed
   // increment or decrement the count variable.
}

使用庫函式查詢給定數字所需的總位數

演算法

  • 步驟1 - 匯入fmt和bits包。

  • 步驟2 - 初始化並定義將實現邏輯的getBits()函式。

  • 步驟3 - 開始main()函式

  • 步驟4 - 初始化無符號整型變數並賦值。

  • 步驟5 - 呼叫getBits()函式。

  • 步驟6 - 將結果儲存在變數中

  • 步驟7 - 在螢幕上列印結果。

示例

使用庫函式獲取給定數字所需總位數的Go語言程式。

package main import ( "fmt" "math/bits" ) // fmt package allows us to print anything on the screen. // bits package allows to perform bitwise operations to unsigned integer values like counting number of bits. func getBits(number uint) int { // getting the binary representation of the above chosen value fmt.Printf("Binary representation of %d is: %b\n", number, number) // initializing a variable to store the results var result int // getting the number of bits in the result variable result = bits.Len(number) // returning back the number of bits return result } func main() { // initializing a variable of unsigned integer data type var number uint // assigning value to the above initialized variable whose bits we wish to calculate number = 65 // calling the getBits() function and passing the number to it as the argument and getting back the result. result := getBits(number) // printing the number of bits of the chosen integer value fmt.Printf("Total number of bits in %d are : %d\n", number, result) }

輸出

Binary representation of 65 is: 1000001
Total number of bits in 65 are : 7

程式碼描述

  • 首先,我們匯入fmt包,它允許我們列印任何內容,以及bits包,它允許我們使用位運算。

  • 然後,我們建立並定義了getBits()函式,該函式計算總位數並返回結果。

  • 然後我們啟動main()函式。

  • 初始化並定義無符號整型變數並賦值。這是我們想要計算其位數的數字。

  • 呼叫getBits()函式並將此數字作為引數傳遞。

  • getBits()函式接收一個無符號整數值並以整型格式返回結果。

  • 然後我們可以列印所選值的二進位制格式,並使用內建的bits.Len()函式獲取構成該數字的總位數的長度。

  • 將結果儲存在一個單獨的變數中並返回此值。

  • 將函式返回的值儲存在main()中。

  • 使用fmt.Printf()函式在螢幕上列印結果。

結論

我們已經成功編譯並執行了Go語言程式,以獲取給定程式所需的總位數,並使用庫函式提供了示例。

更新於:2022年10月25日

432次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始
廣告