面试题16 数值的整数次方
审题很重要
当指数为正数 那么按部就班
当指数为非正数,有0与负数
package question16_power;
/**
* @Classname Solution
* @Description TODO
* @Date 2020/3/9 13:59
* @Created by mmz
*/
public class Solution {
public static double Power(double base,int exponent){
if(base == 0.0){
return 0.0;
}
if(exponent == 0){
return 1;
}else if(exponent <0){
return 1/getPower(base,-exponent);
}else{
return getPower(base,exponent);
}
}
public static double getPower(double base,int exponent){
double result = 1.0;
for(int i =1;i<=exponent;++i){
result *=base;
}
return result;
}
public static void main(String[] args) {
System.out.println(Solution.Power(2, 1));
System.out.println(Solution.Power(2, 0));
System.out.println(Solution.Power(2, -1));
}
}
二刷
package question16_power;
import java.util.Base64;
/**
* @Classname Solution1
* @Description TODO
* @Date 2020/3/31 22:09
* @Created by mmz
*/
public class Solution1 {
static double mathmi(double base ,int exponent){
if(base == 0.0){
return 0;
}
if(exponent == 0){
return 1;
}else if(exponent<0){
return 1/getmi(base,-exponent);
}else{
return getmi(base,exponent);
}
}
static double getmi(double base,int exponent){
double result = base;
if(exponent == 1){
return result;
}
for(int i = 2;i<=exponent;++i){
result *= base;
}
return result;
}
public static void main(String[] args) {
// System.out.println(mathmi(2, 1));
// System.out.println(mathmi(2, 0));
// System.out.println(mathmi(2, -1));
System.out.println(mathmi(2, 3));
}
}
要判断多种情况。
如果底数为0,那么结果直接为0
如果指数可能为三种情况,
若为负数,那么位正数结果的倒数
若为零,结果为1
若为正数,正常进行运算。