Python程序查找表示O(1)复杂度的数字所需的位数
生活随笔
收集整理的這篇文章主要介紹了
Python程序查找表示O(1)复杂度的数字所需的位数
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Problem statement
問題陳述
Find total Number of bits required to represent a number in binary
查找以二進制表示數字所需的總位數
Example 1:
范例1:
input : 10output: 4Example 2:
范例2:
input : 32output : 6Formula used:
使用的公式:
Bits_required = floor(log2(number) + 1)Code:
碼:
# From math module import log2 and floor function from math import log2,floor# Define a function for finding number of bits # required to represent any number def countBits(Num) :bits = floor(log2(Num) + 1)return bitsif __name__ == "__main__" :# assign numberNum = 10# function callprint(countBits(Num))Num = 32print(countBits(Num))Output
輸出量
4 6翻譯自: https://www.includehelp.com/python/find-the-number-of-required-bits-to-represent-a-number-in-O-1-complexity.aspx
總結
以上是生活随笔為你收集整理的Python程序查找表示O(1)复杂度的数字所需的位数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 算法导论 算法_算法导论
- 下一篇: 带有示例的Python File rea