通過自學書籍,他們給了你一些代碼來找出特定數字在一個整數中的數量。他們是如何自動知道使用模10的?這是你作爲程序員在CompSci類中學習技巧的東西嗎?邏輯思維:計算某個數字出現在整數中的次數
def num_zero_and_five_digits(n):
count = 0
while n:
digit = n % 10 # This divides w/10 for remainder. How did they know to use 10?
if digit == 0 or digit == 5: #These can be changed to whatever digits you want.
count = count + 1
n = n/10
return count
我瞭解的代碼,但不擁有它。我的意思是,如果有人問我「寫碼」,將找到一個特定的數字有多少次是一個整數,我會親自 做這樣的事情:
integer = str(22342445)
looker = list(integer)
counter = 0
find = raw_input("What number are you looking for")
for num in looker:
if find == num:
print "We found it!"
counter += 1
print "There are %d, %s's in %s" % (counter, find,integer)
現在,我的主要問題是:
如果有人想要查找整數「10」或更高? 如何解釋第一個解決方案?
您會親自採取哪些措施來提供像第一種解決方案?你會如何「知道」你需要做模10?
這太寬泛了,也可能應該移到數學SO並且也在尋找外部資源。你真的應該把它分解成多個不同的問題。 – 2014-10-18 05:25:57
我會把它削減一點,使其不那麼寬泛。 – Kameron 2014-10-18 05:40:38