Using iteration to work out powers

2019-02-18 03:16发布

问题:

I'm basically trying to rewrite math.pow, I have the following obviously I'm not getting the concept of returning values. What exactly am I doing wrong?

public static int power(int x, int n)
{
    if (n == 0) return 1;
    int i,total;
    for(i = 0; i < n-1 ;i++);
    {   
        total = (x * total);
    }
    return total;


}

回答1:

You need to initialize total to 1.

int total = 1;

You can just rewrite everything to:

public static int power(int x, int n)
{
    int total = 1;
    for(int i = 0; i < n; i++) // i can be declared here directly
    {   
        total = (x * total);
    }
    return total; // total remains 1 if n = 0   
}


回答2:

public static int power(int x, int n)
{
    int total = 1; // Initialized total to 1
    for(int i = 0; i < n; i++)
    {   
        total = x*total;
    }
    return total;


}


回答3:

instead of i < n-1 you should use i <= n-1 or i < n and int total=1. hope it will work.

also remove ; from the for loop end. rewriting the code

public static int power(int x, int n){
        int total=1;
        for(int i = 0;i < n;i++)
            total *= x;
   return total;
}


回答4:

For one, it looks like you meant:

if (n == 0) return 1;

check the power, not the base number.

You're not initialisign total either, using total = x would fix things i think.



回答5:

The variable total starts at 0. So calling total = x*total will always be 0.

You need to initialize total to x.



回答6:

Here is a solution with log(n) complexity instead of linear. Be careful with overflow though.

int pow(int x, int n) {
    int res = 1;
    while(n > 0) {
        if(n % 2 == 1) {
            res = res * x;
        }
        x = x * x;
        n = n / 2;
    }
    return res;
}