计算数字中的位数

问题描述 投票:0回答:6

我写了一个名为

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
作为输出。这是为什么?我该如何纠正?

python filter count
6个回答
2
投票

这是一种

Python3
行为。
/
返回
float
而不是
integer
除法。

将代码更改为:

def count_digit(num):
    if (num//10 == 0):
        return 1
    else:
        return 1 + count_digit(num // 10)

print(count_digit(23))

1
投票

将整数转换为字符串,然后对转换后的字符串使用 len() 方法。除非您也考虑将浮点数作为输入,而不仅仅是整数。


1
投票

假设您总是向函数发送整数并且您要求数学答案,这可能是您的解决方案:

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

1
投票

递归

def count_digit(n):
    if n == 0:
        return 0
    return count_digit(n // 10) + 1

简单

def count_digit(n):
    return len(str(abs(n)))

1
投票

这是一个简单的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)

0
投票

Greg_Kan 建议:

len(str(num))
© www.soinside.com 2019 - 2024. All rights reserved.