zoukankan      html  css  js  c++  java
  • python计算1~2008中0和1的个数

    计算1~2008中所有自然数中1和0的个数总数。
    • 通过自然数的大小划分区间,将自然数每位上的数载入列表,循环计数。
    list = []
    onecount = 0
    zerocount = 0
    for i in range(1,2009):
         if int(i/1000)!=0:                           #thousands
             list.append(int(i/1000))
             list.append(int(i/100)%10)
             list.append(int(i/10)%10)
             list.append(i%10)
             for count in list:
                 if count == 1:
                     onecount = onecount + 1
                 if count == 0:
                     zerocount = zerocount + 1
             list=[]                                    #clear
         elif int(i/100)!=0:                            #hundreds
             list.append(int(i / 100))
             list.append(int(i / 10)%10)
             list.append(i % 10)
             for count in list:
                 if count == 1:
                     onecount = onecount + 1
                 if count == 0:
                     zerocount = zerocount + 1
             list = []                                    #clear
         elif int(i/10)!=0:                              #tens
             list.append(int(i / 10))
             list.append(i%10)
             for count in list:
                 if count == 1:
                     onecount = onecount + 1
                 if count == 0:
                     zerocount = zerocount + 1
             list = []                                  #clear
         else:                                         #single figurea
             if i == 1:
                 onecount = onecount + 1
             if i == 0:
                 zerocount = zerocount + 1
    print('1的个数为:',onecount)
    print('0的个数为:',zerocount)
    • 将数转为字符串,循环统计字符串中‘0’,‘1’的个数。
    #coding:GBK
    #计算0的个数和1的个数
    s0=0
    for i in range(1, 2009):
        c=str(i)
        s0=s0+c.count('0')
    print('1-2008中0的个数为:')
    print(s0)
    s1=0
    for i in range(1, 2009):
        c=str(i)
        s1=s1+c.count('1')
    print('1-2008中1的个数为:')
    print (s1)
  • 相关阅读:
    1523. K-inversions URAL 求k逆序对,,,,DP加树状数组
    Football 概率DP poj3071
    Collecting Bugs poj2096 概率DP
    E. Exposition
    Subsequence
    D. How many trees? DP
    hdu 1542 线段树 求矩形并
    Huge Mission
    2013 ACM/ICPC Asia Regional Chengdu Online hdu4731 Minimum palindrome
    008 jackson的一些使用记录
  • 原文地址:https://www.cnblogs.com/FerrisFu/p/9166490.html
Copyright © 2011-2022 走看看