【Leetcode】Power of Four
2016-05-26 21:52
381 查看
题目链接:https://leetcode.com/problems/power-of-four/
题目:
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?
思路:
观察4个幂次方,发现除了最高位,都是0,且0的个数是偶数,如4=100 16=10000, 8=1000。否则就不是4的power
算法:
public static boolean isPowerOfFour(int num) {
if(num==1)
return true;
if(num==2||num==3)
return false;
if (num<1)
return false;
String binary = Integer.toBinaryString(num);
char c[] = binary.toCharArray();
int count = 0;
for(int i=1;i<c.length;i++){//除了开头全是0
if(c[i]!='0'){
return false;
}else{//统计0的个数
count++;
}
}
if(count!=0&&count%2==0)//有偶数个0
return true;
else
return false;
}
题目:
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?
思路:
观察4个幂次方,发现除了最高位,都是0,且0的个数是偶数,如4=100 16=10000, 8=1000。否则就不是4的power
算法:
public static boolean isPowerOfFour(int num) {
if(num==1)
return true;
if(num==2||num==3)
return false;
if (num<1)
return false;
String binary = Integer.toBinaryString(num);
char c[] = binary.toCharArray();
int count = 0;
for(int i=1;i<c.length;i++){//除了开头全是0
if(c[i]!='0'){
return false;
}else{//统计0的个数
count++;
}
}
if(count!=0&&count%2==0)//有偶数个0
return true;
else
return false;
}
相关文章推荐
- 配置hibernate根据实体类自动建表功能(转载)
- 在centos 上安装jenkins
- 解决不兼容getElementsByClassName
- php核心知识点
- 面向对象设计原则
- 数据结构基础知识(二)
- Internet标准时间RFC3339格式说明
- UE4之SlateUI系统初探
- 剑指Offer之在O(1)时间删除链表节点(题13)
- 【Leetcode】Different Ways to Add Parentheses
- 原理设计思想
- 剑指Offer——翻转单词顺序VS左旋转字符串
- C++快速入门-命名空间
- 链表相关题目的实现
- 工厂方法模式及php实现
- Java中HashMap遍历的两种方式比较
- 【Leetcode】Patching Array
- 联想功能字符串的提取(c)
- cocoaPods安装步骤
- 获取本机IP地址