我写了一个名为
count_digit
的函数:
# Write a function which takes a number as an input
# It should count the number of digits in the number
# And check if the number is a 1 or 2-digit number then return True
# Return False for any other case
def count_digit(num):
if (num/10 == 0):
return 1
else:
return 1 + count_digit(num / 10);
print(count_digit(23))
我得到
325
作为输出。这是为什么?我该如何纠正?
这是一种
Python3
行为。 /
返回 float
而不是 integer
除法。
将代码更改为:
def count_digit(num):
if (num//10 == 0):
return 1
else:
return 1 + count_digit(num // 10)
print(count_digit(23))
将整数转换为字符串,然后对转换后的字符串使用 len() 方法。除非您也考虑将浮点数作为输入,而不仅仅是整数。
假设您总是向函数发送整数并且您要求数学答案,这可能是您的解决方案:
import math
def count_digits(number):
return int(math.log10(abs(number))) + 1 if number else 1
if __name__ == '__main__':
print(count_digits(15712))
# prints: 5
def count_digit(n):
if n == 0:
return 0
return count_digit(n // 10) + 1
def count_digit(n):
return len(str(abs(n)))
这是一个简单的Python解决方案;
num=23
temp=num #make a copy of integer
count=0
#This while loop will run unless temp is not zero.,so we need to do something to make this temp ==0
while(temp):
temp=temp//10 # "//10" this floor division by 10,remove last digit of the number.,means we are removing last digit and assigning back to the number;unless we make the number 0
count+=1 #after removing last digit from the number;we are counting it;until the number becomes Zero and while loop becomes False
print(count)
Greg_Kan 建议:
len(str(num))