How do I count the trailing zeros in integer?

后端 未结 8 1100
北恋
北恋 2021-01-08 00:26

I am trying to write a function that returns the number of trailing 0s in a string or integer. Here is what I am trying and it is not returning the correct values.

         


        
相关标签:
8条回答
  • 2021-01-08 00:36

    May be you can try doing this. This may be easier than counting each trailing '0's

    def trailing_zeros(longint):
        manipulandum = str(longint)
        return len(manipulandum)-len(manipulandum.rstrip('0'))
    
    0 讨论(0)
  • 2021-01-08 00:37

    You could just:

    1. Take the length of the string value of what you're checking
    2. Trim off trailing zeros from a copy of the string
    3. Take the length again, of the trimmed string
    4. Subtract the new length from the old length to get the number of zeroes trailing.
    0 讨论(0)
  • 2021-01-08 00:37

    Here are two examples of doing it:

    1. Using rstrip and walrus := operator. Please notice that it only works in Python 3.8 and above.
    
    def end_zeros(num):
        return len(s := str(num)) - len(s.rstrip("0"))
    
    1. Using findall() regular expression (re) function:
    
    from re import findall
        
    def end_zeros(num):
        return len(findall("0*$", str(num))[0])
    
    0 讨论(0)
  • 2021-01-08 00:43

    The question asks to count the trailing zeros in a string or integer. For a string, len(s) - len(s.rstrip('0')) is fine. But for an integer, presumably you don't want to convert it to a string first. In that case, use recursion:

    def trailing_zeros(longint):
        assert(longint)
        return ~longint % 2 and trailing_zeros(longint/2) + 1
    
    0 讨论(0)
  • 2021-01-08 00:51

    For strings, it is probably the easiest to use rstrip():

    In [2]: s = '23989800000'
    
    In [3]: len(s) - len(s.rstrip('0'))
    Out[3]: 5
    
    0 讨论(0)
  • 2021-01-08 00:54

    I found two ways to achieve this, one is already mentioned above and the other is almost similar:

    manipulandum.count('0') - manipulandum.rstrip('0').count('0')
    

    But still, I'm looking for some better answer.

    0 讨论(0)
提交回复
热议问题