zoukankan      html  css  js  c++  java
  • 判断一个整数是否是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)
  • 相关阅读:
    Tomcat 7 自动加载类及检测文件变动原理
    ElasticSearch查询
    ElasticSearch集群的基本原理
    ElasticSearch基础
    hbase时间不同步问题引起的bug
    IDEA运行异常java.lang.NoClassDefFoundError: org/apache/spark/api/java/function/Function
    spark任务提交之SparkLauncher
    spark调优(二)-Apache Spark 内存管理详解
    spark调优(一)-开发调优,数据倾斜,shuffle调优
    spark内核源码深度剖析(1)--Spark内核架构深度剖析
  • 原文地址:https://www.cnblogs.com/zhangtebie/p/11185907.html
Copyright © 2011-2022 走看看