How do I count the trailing zeros in integer?

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

提交回复
热议问题