Python calculates the number of 0 and 1 in 1~2008

Source: Internet
Author: User

Calculates the total number of 1 and 0 in all natural numbers in the 1~2008.
    • By the size of the natural number to divide the interval, the number of natural number per bit load into the list, cycle count.
List =[]onecount=0zerocount=0 forIinchRange (1,2009):     ifInt (i/1000)!=0:#thousandsList.append (int (i/1000)) list.append (int (i/100)%10) list.append (int (i/10)%10) list.append (i%10)          forCountinchlist:ifCount = = 1: Onecount= Onecount + 1ifCount = =0:zerocount= Zerocount + 1List=[]#Clear     elifInt (i/100)!=0:#hundredsList.append (int (i/100)) list.append (int (i/10)%10) list.append (i% 10)          forCountinchlist:ifCount = = 1: Onecount= Onecount + 1ifCount = =0:zerocount= Zerocount + 1List= []#Clear     elifInt (I/10)!=0:#TensList.append (int (I/10)) List.append (i%10)          forCountinchlist:ifCount = = 1: Onecount= Onecount + 1ifCount = =0:zerocount= Zerocount + 1List= []#Clear     Else:#Single Figurea         ifi = = 1: Onecount= Onecount + 1ifi = =0:zerocount= Zerocount + 1Print('the number of 1 is:', Onecount)Print('the number of 0 is:', Zerocount)
    • Converts a number to a string, looping through the count of ' 0 ', ' 1 ' in the string.
#CODING:GBK#calculates the number of 0 and the number of 1s0=0 forIinchRange (1, 2009): C=Str (i) S0=s0+c.count ('0')Print('the number of 1-2008 in 0 is:')Print(S0) S1=0 forIinchRange (1, 2009): C=Str (i) S1=s1+c.count ('1')Print('the number of 1-2008 in 1 is:')Print(S1)

Python calculates the number of 0 and 1 in 1~2008

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.