文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>python code for

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)
相关阅读 更多 +
排行榜 更多 +
找茬脑洞的世界安卓版

找茬脑洞的世界安卓版

休闲益智 下载
滑板英雄跑酷2手游

滑板英雄跑酷2手游

休闲益智 下载
披萨对对看下载

披萨对对看下载

休闲益智 下载