zoukankan      html  css  js  c++  java
  • [python语法巩固][leetcode326][Power of Three]

    题目大意

    让你判断一个int是否为3的幂;

    最简单的思路

    C++

    class Solution {
    public:
        bool isPowerOfThree(int n) {
            for(long long i=1;i<=n;i=i*3LL)
            {
                if(i==n) return true;
            }
            return false;
        }
    };

    Python

    第一种写法…很低效..因为不会类似C++的for..

    class Solution(object):
        def isPowerOfThree(self, n):
            """
            :type n: int
            :rtype: bool
            """
            for x in range(30):
                if 3**x==n:
                    return True;
            return False;

    第二种写法 类似C++的,但是只用用while实现
    Python的缩进真是让人理解不能 空格TAP混用不行??????
    需要修改Sublime的设置

    class Solution(object):
        def isPowerOfThree(self, n):
            x=1;
            while x <= n:
                if x==n :
                    return True;
                x=x*3;
            return False;

    sublime设置

    sublime 默认是tab 缩进,修改成4个空格缩进 “首选项” —>”设置–更多” —>’”特定的语法–用户”
    添加如下内容 点击(此处)折叠或打开 {
    “tab_size”: 4,
    “translate_tabs_to_spaces”: true }

    要求不准用循环

    1.利用对数函数,再判断是否为整数。

    C++

    精度误差要控制的很细 1e-10才能过,这样的程序速度快,但是存在一定误差。
    注意取整的时候要加一个0.5才是 四舍五入!!!刘书上说过。

    class Solution {
    public:
        bool static isPowerOfThree(int n) {
            double a=log(n)/log(3);
            printf("%lf
    ",a);
            int b=(int)(a+0.5);
            printf("%d
    ",b);
            if(abs(a-b)<1e-10) return true;
            else return false ;
        }
    };

    Python

    round(val,位数) 四舍五入
    Python 中math.log() 接收到0会报错

    class Solution(object):
        def isPowerOfThree(self, n):
            if n>0:
                a=math.log(n)/math.log(3.0);
            else :
                a=0.5;
            b=round(a,0)
            if abs(a-b)<1e-10:
                return True;
            else:
                return False;

    终极想法

    还有一种想法就是Python打表 switch ,应该是最简单的了。

  • 相关阅读:
    【题解】 [yLOI2019] 梅深不见冬
    【题解】[CSP-S2019] Emiya 家今天的饭
    【题解】Acwing400. 太鼓达人
    【题解】[ZJOI2007]最大半连通子图
    【题解】Acwing395. 冗余路径
    【题解】CF487E Tourists
    “𣎴” 这个字存Mysql Incorrect string value: 'xF0xA3x8ExB4' for column 'msg' at row 1
    logminer分析异机db的归档日志(外部文件)
    logminer存储在外部文件(external file)
    logminer分析在线redo log
  • 原文地址:https://www.cnblogs.com/zy691357966/p/5480295.html
Copyright © 2011-2022 走看看