[python语法巩固][leetcode326][Power of Three]

来源:互联网 发布:淘宝客教学视频 编辑:程序博客网 时间:2024/06/05 00:23

题目大意

让你判断一个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\n",a);        int b=(int)(a+0.5);        printf("%d\n",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 ,应该是最简单的了。

1 0
原创粉丝点击