เมื่อต้องการตรวจสอบว่าเลขในฐาน (base) ใดฐานหนึ่งมีศูนย์ติดต่อกัน (consecutive zeros) หรือไม่ สามารถแปลงเลขเป็นฐานนั้น แล้วตรวจสอบรูปแบบของตัวเลข
โค้ดตัวอย่าง
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: ฟังก์ชันหลัก รับเลข N และฐาน Kconvert_to_base: แปลงเลขฐานสิบเป็นฐาน K (เก็บผลลัพธ์เป็น int ที่ตัวเลขแต่ละหลักคือ digit ในฐาน K)check_n: ตรวจสอบว่ามีศูนย์ติดกันหรือไม่ โดยอ่าน digit จากขวาไปซ้ายตัวอย่าง: 8 ในฐาน 2 คือ 1000 — มีศูนย์ติดกัน 3 ตัว แต่ฟังก์ชัน
check_nมีตรรกะเฉพาะ: คืน True ก็ต่อเมื่อมีศูนย์เพียงตัวเดียว (ไม่ติดกัน) — อาจต้องปรับตรรกะตามความต้องการจริง
วิธีที่ง่ายกว่า: แปลงเป็น string แล้วตรวจสอบ '00' in str_number