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