使用Python檢查給定進位制的數字是否包含連續的0
當需要檢查一個數字在特定進位制下是否包含連續的零時,我們定義一個方法,該方法將數字和進製作為引數,並使用另一個方法根據特定進位制是否存在返回“是”或“否”。
下面是演示:
示例
def check_consecutive_zero(N, K):
my_result = convert_to_base(N, K)
if (check_n(my_result)):
print("Yes")
else:
print("No")
def convert_to_base(N, K):
weight = 1
s = 0
while (N != 0):
r = N % K
N = N//K
s = r * weight + s
weight*= 10
return s
def check_n(N):
res = False
while (N != 0):
r = N % 10
N = N//10
if (res == True and r == 0):
return False
if (r > 0):
res = False
continue
res = True
return True
N, K = 8, 2
print("Does the number have consecutive zeroes in the base ?")
check_consecutive_zero(N, K)輸出
Does the number have consecutive zeroes in the base ? No
解釋
定義了一個名為“check_consecutive_zero”的方法,該方法接受數字和進製作為引數。
使用“convert_to_base”方法將給定數字轉換為特定進位制。
根據輸出是否為特定進位制,返回“是”或“否”。
使用“check_n”方法檢查數字是否為0。
定義N和K的值。
透過傳遞N和K來呼叫“check_consecutive_zero”方法。
在控制檯上顯示輸出。
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP