2011-12-21 76 views
6

我想寫一個函數,返回一個字符串或整數結尾0的數量。這是我正在嘗試,並沒有返回正確的值。在Python中,如何計算字符串或整數中的尾隨零?

def trailing_zeros(longint): 
    manipulandum = str(longint) 
    x = 0 
    i = 1 
    for ch in manipulandum: 
     if manipulandum[-i] == '0': 
      x += x 
      i += 1 
     else: 
      return x 
+0

「沒有返回正確的值」?它有助於您提供您正在使用的測試用例以及預期的答案和答案。 – 2011-12-21 16:52:26

+0

本網站的新用戶感謝您的輸入。 – 2011-12-21 17:07:27

+0

我想你的意思是說'i + = 1'。 – 2011-12-21 16:52:30

回答

8

可能是你可以嘗試這樣做。這可能比計算更容易每個後「0'

def trailing_zeros(longint): 
    manipulandum = str(longint) 
    return len(manipulandum)-len(manipulandum.rstrip('0')) 
+0

我可以告訴我要去喜歡這個網站。你們好棒。 – 2011-12-21 17:06:38

19

對於字符串,這大概是最容易使用的rstrip()

In [2]: s = '23989800000' 

In [3]: len(s) - len(s.rstrip('0')) 
Out[3]: 5 
+0

+1:聰明..... – 2011-12-21 16:54:28

1

你可能只是:

  1. 拿你檢查什麼
  2. 的字符串值的長度
  3. 從字符串副本中刪除尾隨零
  4. 取長度再次,修剪後的字符串
  5. 從舊的長度減去新的長度以獲得零的尾數。
0

我發現了兩種方式來實現這一目標,一個是上面已經提到,另一個是幾乎相同:

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

但儘管如此,我尋找更好的答案。

相關問題