leecode 解题总结:326. Power of Three
来源:互联网 发布:arcgis js heatmap 编辑:程序博客网 时间:2024/06/07 16:05
#include <iostream>#include <stdio.h>#include <vector>#include <string>using namespace std;/*问题: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的次方。尽量不要使用循环或者递归。3^0 =1=000000013^1=3=000000113^2=9=000010013^3=27=000110113^4=81= 01010001分析这个有什么特点我们知道2^n的特点是只有一位上面是1。因此可以用n&(n-1)来判定3^n=(2+1)^n=2^0 * 1^n + C(n,1)2^1 * 1^(n-1) + ... + C(n,n)2^n * 1^0 =C(n,0)2^0 + C(n,1)2^1 + ... + C(n,n)2^n因为(a+b)^n=C(n,k)*a^k * b^(n-k),然后k属于0到n这个公式比较复杂。如果要循环:每次除以3看是否能够除尽。递归和循环一个处理方式。不能使用,要么做减法,要么做加法。没有想到参考解法http://blog.csdn.net/ebowtang/article/details/50485622采用log函数,3^n以3为底数的log值是整数,但是要用log10(n) / log(3)不会带来精度问题,然后比较double和转化为int的结果相减是否为0输入:12381输出:truefalsetruetrue关键:1 参考解法http://blog.csdn.net/ebowtang/article/details/50485622采用log函数,3^n以3为底数的log值是整数,但是要用log10(n) / log(3)不会带来精度问题,然后比较double和转化为int的结果相减是否为02 还可以枚举出所有3^n次方,或者用不超过int的3^n的最大值除以给定数余数为0即可*/class Solution {public: bool isPowerOfThree(int n) { double result = log10(n) / log10(3);return (result - int(result)) == 0 ? true : false; }};void process(){ int num; Solution solution; while(cin >> num ) { bool result = solution.isPowerOfThree(num); if(result) { cout << "true" << endl; } else { cout << "false" << endl; } }}int main(int argc , char* argv[]){process();getchar();return 0;}
0 0
- leecode 解题总结:326. Power of Three
- leecode 解题总结:342. Power of Four
- [leetcode] 326. Power of Three 解题报告
- 326. Power of Three LeetCode解题报告
- LeetCode 326. Power of Three 解题报告
- [Leetcode] 326. Power of Three 解题报告
- 326. Power of Three
- 326. Power of Three
- 326. Power of Three
- 326. Power of Three
- 326. Power of Three
- 326. Power of Three
- 326. Power of Three
- 326. Power of Three
- 326. Power of Three
- 326. Power of Three
- 326. Power of Three
- 326. Power of Three
- 大中型Web站点解决高并发访问的优化方案
- 2017年伊始你绝对想尝试的25个新安卓库
- CREELINKS平台_处理器CeAd资源使用说明(CeAd的配置与使用)
- 解决window.showModalDialog在Firefox无法支持
- 重新编译src.zip方便调试JDK
- leecode 解题总结:326. Power of Three
- Linux特殊权限:SUID、SGID、SBIT
- Java多线程核心技术(三):线程间通信
- android应用退出后在任务管理器隐藏
- OpenVPN GUI连接显示黄色
- jsp页面关于Java,js和html的加载顺序
- Python 图像处理: 生成二维高斯分布蒙版
- 安卓6.0之后——动态获取权限封装
- Oracle数据库用户查询常用命令