範囲内の未設定ビットをカウントするPythonプログラム。
正の数とビットの範囲が与えられます。私たちのタスクは、範囲内の未設定ビットをカウントすることです。
Input : n = 50, starting address = 2, ending address = 5 Output : 2
2〜5の範囲に「2」の未設定ビットがあります。
アルゴリズム
Step 1 : convert n into its binary using bin(). Step 2 : remove first two characters. Step 3 : reverse string. Step 4 : count all unset bit '0' starting from index l-1 to r, where r is exclusive.
サンプルコード
# Function to count unset bits in a range
def countunsetbits(n,st,ed):
# convert n into it's binary
bi = bin(n)
# remove first two characters
bi = bi[2:]
# reverse string
bi = bi[-1::-1]
# count all unset bit '0' starting from index l-1
# to r, where r is exclusive
print (len([bi[i] for i in range(st-1,ed) if bi[i]=='0']))
# Driver program
if __name__ == "__main__":
n=int(input("Enter The Positive Number ::>"))
st=int(input("Enter Starting Position"))
ed=int(input("Enter Ending Position"))
countunsetbits(n,st,ed)
出力
Enter The Positive Number ::> 50 Enter Starting Position2 Enter Ending Position5 2
-
配列内の反転をカウントするPythonプログラム
この記事では、以下に示す問題ステートメントの解決策について学習します。 問題の説明 −リストが表示されます。必要な反転をカウントして表示する必要があります。 反転カウントは、配列をソートするために必要なステップ数をカウントすることによって取得されます。 次に、以下の実装のソリューションを見てみましょう- 例 # count def InvCount(arr, n): inv_count = 0 for i in range(n): for j in range(i + 1, n):
-
数値の合計ビットをカウントするPythonプログラムを作成しますか?
最初に数値を入力し、bin()関数を使用してこの数値をバイナリに変換し、次に出力文字列の最初の2文字「0b」を削除し、次にバイナリ文字列の長さを計算します。 例 Input:200 Output:8 説明 Binary representation of 200 is 10010000 アルゴリズム Step 1: input number. Step 2: convert number into its binary using bin() function. Step 3: remove first two characters ‘0b’ of output binary st