/**
* 计算某个数的n次方
*/
public class Pow {
public static void main(String[] args) {
System.out.println (simpleN(2,10));
System.out.println (simpleLogN(2, 10));
}
private static int simpleN(int i, int n) {
int res = 1;
int absN = Math.abs (n);
while(absN > 0){
res *= i;
absN--;
}
return n > 0 ? res : 1 / res;
}
/**
* 2 10
* 10&1 0 1 4 5
* 5&1 1 4 16 2
* 2&1 0 4 256 1
* 1&1 1 1024 256 * 256 0
* 1024
* 2 * 2 * 4 * 4 * 4 * 4
* @param i
* @param n
* @return
*/
private static int simpleLogN(int i, int n) {
int res = 1;
long absN = Math.abs (n);
while(absN != 0){
if((absN & 1) == 1) {
res *= i;
}
i *= i;
absN >>= 1;
}
return n > 0 ? res : 1 / res;
}
}
2 10 2^10=2^8*2^2 即1010
说明:若位数是0那么用i^2,若1那么res*=i
&值 前res 后res i
10&1 0 1 1 4 5
5&1 1 1 4 16 2
2&1 0 4 4 256 1
1&1 1 4 1024 256^2 0