python code for
时间:2011-01-14 来源:Donal
cat countone.py
#!/usr/bin/python
#
# Find the number of 1 in the integers between 1 and N
# Input: N - an integer
# Output: the number of 1 in the integers between 1 and N
#
def countone(N):
#make sure that N is an integer
N = int(N)
#convert N to chars
a = str(N)
#the lenth is string a
n = len(a)
i = 0
count = 0
while (i < n):
if(i == 0):
if(int(a[i]) == 1 ):
count += int(a[1:])+1
elif(int(a[i]) > 1):
count += 10 ** (n-1)
elif(i == n - 1):
if(int(a[i]) == 0):
count += int(a[:n-1])
else:
count += int(a[:n-1]) + 1
else:
if(int(a[i]) == 0):
count += int(a[:i]) * (10 ** (n - i - 1))
elif(int(a[j]) == 1):
count += int(a[:i]) * (10 ** (n - i - 1)) + int(a[i+1:]) + 1
else:
count += (int(a[:i]) + 1) * (10 ** (n - i -1))
i += 1
return count
#Test code
import sys
if(__name__ == "__main__"):
N = int(sys.argv[1])
n = countone(N)
print "the number of '1' between 1 and %d is %d" % (N,n)
相关阅读 更多 +