【小熊刷题】power of two, pow(x, n) <Leetcode 231, 50 Java>
2015-09-05 04:02
633 查看
Question 1
Power of TwoGiven an integer, write a function to determine if it is a power of two.
**Difficulty: Easy
my solution 1
divide by 2 and check mod, if not 0, and check if it is the first bit of the num, since if power of two should only have one 1 at the beginning and follow by 0public class Solution { public boolean isPowerOfTwo(int n) { if(n <= 0) return false; while(n % 2 == 0){ n /= 2; } return (n==1); } }
Solution 2
bit mask1000&0111 = 0
public class Solution { public boolean isPowerOfTwo(int n) { if(n <= 0) return false; return (n & (n-1))==0; } }
Question 2
Implement pow(x, n).My Solution
Divide and conquer**Difficulty: Medium
*be careful about n<0
public class Solution { //divide and conqur public double myPow(double x, int n) { if(x == 0) return x; if(n == 0) return 1; if(n == 1) return x; if(n == -1) return 1/x; int r = n/2; int l = n - r; double p = myPow(x, r); return p*p*myPow(x, n - 2*r); } }
相关文章推荐
- Java堆.栈和常量池 笔记
- Java设计模式 之 代理模式
- Java多线程(1)
- Action参数缓存-Spring单例
- Java使用Calendar类在控制台输出指定年份和月份的日历
- JAVA注释
- java将float字符串还原为float数字
- Java Spring AOP用法
- Injecting Spring Beans into Java Servlets
- Java之工具-------Junit自己的测试工具MyJUnit
- Java虚拟机内存模型
- Atitit. 衡量项目规模 ----包含的类的数量 .net java类库包含多少类 多少个api方法??
- Atitit. 衡量项目规模 ----包含的类的数量 .net java类库包含多少类 多少个api方法??
- Atitit. 衡量项目规模 ----包含的类的数量 .net java类库包含多少类 多少个api方法??
- java安全沙箱(四)之安全管理器及Java API
- Java 8函数式编程学习笔记
- Java日期和时间的那些事
- mysql java.sql.SQLException: Unknown system variable 'language'
- Java中获取键盘输入值的三种方法
- Java并发容器并发集合