How do I count the trailing zeros in integer?

后端 未结 8 1101
北恋
北恋 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:54

    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"))

    2. Using re.findall() function:

      from re import findall

      def end_zeros(num): return len(findall("0*$", str(num))[0])

    0 讨论(0)
  • 2021-01-08 00:56

    if you want to count how many zeros at the end of your int:

       def end_zeros(num):
            new_num = str(num)
            count = len(new_num) - len(new_num.rstrip("0"))
            return count
    
    
    
        print(end_zeros(0))  # == 1
        print(end_zeros(1))  # == 0
        print(end_zeros(10))  # == 1
        print(end_zeros(101))  # == 0
        print(end_zeros(245))  # == 0
        print(end_zeros(100100))  # == 2
    
    0 讨论(0)
提交回复
热议问题