您的位置:首页 > 编程语言 > Java开发

【小熊刷题】power of two, pow(x, n) <Leetcode 231, 50 Java>

2015-09-05 04:02 633 查看

Question 1

Power of Two

Given 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 0

public class Solution {
public boolean isPowerOfTwo(int n) {
if(n <= 0) return false;
while(n % 2 == 0){
n /= 2;
}
return (n==1);
}
}


Solution 2

bit mask

1000&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);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: