Power of Four
2016-07-06 15:51
197 查看
Given an integer (signed 32 bits), write a function to check whether it is a power of 4.
Example:
Given num = 16, return true. Given num = 5, return false.
Follow up: Could you solve it without loops/recursion?
Credits:
Special thanks to
@yukuairoy for adding this problem and creating all test cases.
#include<iostream>
#include<algorithm>
using namespace std;
bool judge(int n);
int main()
{
int a[] = { 4, 16, 30, 64, 88, 24 };
for (int i = 0; i < sizeof(a) / sizeof(a[0]); i++)
{
cout << judge(a[i]) << endl;
}
system("pause");
return 0;
}
bool judge(int n)
{
/*while (n % 4 == 0)
n = n / 4;
return n == 1;*/
return (n > 0 && int(log10(n) / log10(4)) - log10(n) / log10(4) == 0);
}
Example:
Given num = 16, return true. Given num = 5, return false.
Follow up: Could you solve it without loops/recursion?
Credits:
Special thanks to
@yukuairoy for adding this problem and creating all test cases.
#include<iostream>
#include<algorithm>
using namespace std;
bool judge(int n);
int main()
{
int a[] = { 4, 16, 30, 64, 88, 24 };
for (int i = 0; i < sizeof(a) / sizeof(a[0]); i++)
{
cout << judge(a[i]) << endl;
}
system("pause");
return 0;
}
bool judge(int n)
{
/*while (n % 4 == 0)
n = n / 4;
return n == 1;*/
return (n > 0 && int(log10(n) / log10(4)) - log10(n) / log10(4) == 0);
}
相关文章推荐
- hive-1.2.1配置hiveserver2
- Android使用SVG矢量图打造酷炫动效! 以及用ps生成vector
- SCI EI收录
- 详解计数排序算法及C语言程序中的实现
- 碰撞检测算法:点和矩形碰撞、点和圆形碰撞、矩形碰撞、圆形碰撞
- java面试中的高并发的问题
- 微信公众平台下Access Token的概念及获取方法
- linux 系统、命令、软件
- iOS绘图二
- 防止多次触发
- Android 动画
- 剑指Offer:面试题15——链表中倒数第k个结点(java实现)
- UNIX_C 链表贪吃蛇游戏_吃苹果可生长代码——<.c 测试文件文件>
- shell 中数组使用
- Android 动画
- 【android】git常用命令合集
- 梯度下降法(Gradient Descent)
- zepto源码研究 - zepto.js (zepto.init)
- app_name is not translated
- 策略路由PBR