判断一个整数是否是2整数次幂三种方法
#encode=utf-8
import time
print u"写一个方法判断一个数是否能被2整除"
def whole1(x):
try:
n=0
x=int(x)
if x<2:
print u"{0}不是2".format(x)
while x>1:
if x%2!=0:
print u"number不是2整次幂"
return False
x/=2.0
n+=1
print u"2的{0}次方".format(n)
return True
except Exception,e:
print u"程序出现错误{0[:]}".format(e.message)
def whole2(x):
try:
x=int(x)
result="{0:b}".format(x)
if result.count("1")==1 and result[0]=="1":
print u"{0}能被2整除".format(x)
else:
print u"{0}不能被2整除".format(x)
except Exception,e:
print u"程序出现错误{0[:]}".format(e.message)
def whole3(x):
try:
n=0
x=int(x)
if x<2:
print u"{0}不是2".format(x)
while x>1:
if x%2!=0:
print u"number不是2整次幂"
return False
x=x>>1
n+=1
print u"2的{0}次方".format(n)
return True
except Exception,e:
print u"程序出现错误{0[:]}".format(e.message)
if __name__=="__main__":
time1=time.time()
number=raw_input("输入一个整数: ".decode("utf-8").encode("gbk"))
print "_"*20
for i in range(1,4):
print u"第{0}个程序执行结果: ".format(i)
eval_r("whole{0}".format(i)+"(number)")
print "_"*20
print u"程序执行完耗时{0}".format(time.time()-time1)