计算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)
原文地址:https://www.cnblogs.com/FerrisFu/p/9166490.html
时间: 2024-10-28 12:29:20