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);
}
}