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)
  • 相关阅读:
    第七周 10.11-10.17
    第六周 10.4-10.10
    2015 ACM/ICPC Asia Regional Hefei Online
    cryptopals S1-6
    cryptopals S1-5
    cryptopals S1-4
    Cryptopals S1-3
    Crptopals S1-2
    Crptopals S1-1
    anaconda the procedure entry point openssl_sk_new_reserve could not be located in the dynamic link library libssl-1_1-x64.DLL
  • 原文地址:https://www.cnblogs.com/FerrisFu/p/9166490.html
Copyright © 2011-2022 走看看