輸入正整數 n,輸出其十進制位數。限制:不能使用 len(str(n))、math.log10 等庫函數,僅允許四則運算與循環。
反覆除以 10 計數,直到商為 0。
def count_digits(n):
count = 0
while n > 0:
n //= 10
count += 1
return count
# 測試
print(count_digits(123456)) # 6
print(count_digits(0)) # 0 (題目說正整數,0 特殊處理)
def count_digits_v2(n):
if n == 0: return 1
count = 0
temp = n
while temp:
temp //= 10
count += 1
return count
這是經典的「位數計算」面試題,考察對整數除法與循環不變量的理解。