[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
- [python语法巩固][leetcode326][Power of Three]
- leetcode326. Power of Three
- leetcode326: Power of Three
- leetcode326[easy]--- Power of Three
- LeetCode326. Power of Three一行代码解决
- 326. Power of Three [easy] (Python)
- leetcode(11),Power of Three(python)
- [leetcode: Python]326.Power of Three
- leetcode Power of Three
- Leetcode: Power of Three
- LeetCode Power of Three
- 326. Power of Three
- Leetcode230: Power of Three
- Power of Three
- [leetcode]Power of Three
- LeetCode-Power of Three
- leetcode power of three
- 64. Power of Three
- Tomcat配置常见错误以及解决方案
- 木兰花
- zmq中zmq_poll()函数介绍
- Codeforces Round #334 (Div. 2) B. More Cowbell
- spi子系统 赏析
- [python语法巩固][leetcode326][Power of Three]
- Linux系统中System.map的解析
- C++学习笔记41——重载操作符之下标操作符
- Codeforces Round #334 (Div. 2) C. Alternative Thinking
- Algorithm Intro - Count Sort
- HDOJ 1290 献给杭电五十周年校庆的礼物 (数学—平面分割空间)
- struts2 基于XML配置方式实现校验(指定方法)
- 反射之获取父类
- 概率、随机数、随机数生成函数(面试题)