简体   繁体   English

计算数字位数而无需字符串操作

[英]Counting digits of number with no string operations

Im trying to write a function which counts the number of digits in a number - with no string operation. 我试图写一个函数来计算一个数字的位数-没有string操作。 here is my code: 这是我的代码:

def count_digits(n):
    count_list=[]
    while (n>0):
        n=n%10
        i=n
        count_list.append(i)
        n=n/10
        return len(count_list)

n=12345
print count_digits(n)

By using % i get the last digits - in order to add it to a list. 通过使用%我得到了最后一位数字-以便将其添加到列表中。 By using / i throw the digit from the number. 通过使用/我从数字中抛出数字。

The script does not work. 该脚本不起作用。 For each n i put, the script just prints 1 . 对于每输入n ,脚本仅输出1

Thanks! 谢谢!

There are several problems to your code: 您的代码有几个问题:

  • The return statement should be outside of the loop. return语句应该在循环之外。
  • The n = n % 10 statement modifies n , making it impossible to get the other digits. n = n % 10语句修改了n ,使得不可能获得其他数字。
  • I'd use the integer division operator // . 我会使用整数除法运算符// In Python 3, n / 10 would give a floating point number. 在Python 3中, n / 10将给出一个浮点数。
  • Like ShadowRanger said, the current solution considers 0 as having 0 digits. 就像ShadowRanger所说的那样,当前解决方案将0视为具有0位数字。 You need to check whether n is 0 . 您需要检查n是否为0

Here is a corrected version of your code: 这是您的代码的更正版本:

def count_digits(n):
    if n == 0:
        return 1
    count_list = []
    while n > 0:
        count_list.append(n % 10)
        n = n // 10
    return len(count_list)

Also, as it was said in the comments, since your goal is just to count the digits, you don't need to maintain a list: 另外,正如评论中所述,由于您的目标只是计算数字,所以您无需维护列表:

def count_digits(n):
    if n == 0:
        return 1
    count = 0
    while n > 0:
        n = n // 10
        count += 1
    return count

count_list stores the digits. count_list存储数字。

def count_digits(n):
    count_list=[]
    while (n>0):
        count_list.append(n%10)
        n-=n%10
        n = n/10
    return count_list

n=12345
print len(count_digits(n))

Without using a list 不使用清单

def count_digits(n):
   count_list=0
   while (n>0):
       count_list+=1
       n-=n%10
       n = n/10
   return count_list

n=12345
print count_digits(n)

Perhaps you can try this, a much simpler approach. 也许您可以尝试这种更简单的方法。 No lists involved :) 没有涉及的列表:)

def dcount(num):
    count = 0
    if num == 0:
        return 1
    while (num != 0):
        num /= 10
        count += 1
    return count

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM