leetcode笔记:Power of Three
2016-01-10 17:17
423 查看
一. 题目描述
Given an integer, write a function to determine if it is a power of three.
Follow up: Could you do it without using any loop / recursion?
二. 题目分析
题目的大意很简单,给出一个整数,判断这个整数是不是3的整数次幂。下面提示尽量不适用循环和递归来实现,因此这里给出两种实现方法,其中第一种循环方式的耗时更少。
三. 示例代码
Given an integer, write a function to determine if it is a power of three.
Follow up: Could you do it without using any loop / recursion?
二. 题目分析
题目的大意很简单,给出一个整数,判断这个整数是不是3的整数次幂。下面提示尽量不适用循环和递归来实现,因此这里给出两种实现方法,其中第一种循环方式的耗时更少。
三. 示例代码
[code]class Solution { public: bool isPowerOfThree(int n) { while (n >= 1) { if (n == 1 || n == 3) return true; else { if (n % 3) break; n /= 3; } } return false; } };
[code]class Solution { public: bool isPowerOfThree(int n) { if (n < 1) return 0; int maxPow3 = log10(INT_MAX) / log10(3); int maxPow3Val = pow(3, maxPow3); return maxPow3Val % n == 0; } };
相关文章推荐
- 蜗牛历险记(一) 平台搭建
- 数据结构之散列表实现
- orm2 中文文档 7. 创建和更新记录
- linux安装后简易配置
- 奇异值分解
- 机器学习(七):SVM
- 列表与数组
- 读<<人人都是产品经理>>
- LeetCode208. Implement Trie (Prefix Tree)实现前缀树
- c++ lamda表达式的注意事项
- Tomcat安装及配置教程
- Ubuntu搭建web server
- Block 使用的小结 有转的成分
- orm2 中文文档 6. 查找记录
- 基于Node.js的强大爬虫 能直接发布抓取的文章哦
- 架构之路:nginx与IIS服务器搭建集群实现负载均衡(二)
- LeetCode:Longest Common Prefix
- UVA How Big Is It?
- Hibernate实体类注解
- hdu 2552 三足鼎立