Java 用迭代法求幂

Java 用迭代法求幂,java,iteration,Java,Iteration,我基本上是想重写math.pow,我有以下几点很明显,我没有得到返回值的概念。我到底做错了什么 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; } 公共静态整数功率(整数x,整数n) {

我基本上是想重写math.pow,我有以下几点很明显,我没有得到返回值的概念。我到底做错了什么

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;


}
公共静态整数功率(整数x,整数n)
{
如果(n==0)返回1;
int i,总计;
对于(i=0;i
您需要将总数初始化为1

int total = 1;
您可以将所有内容重写为:

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   
}
公共静态整数功率(整数x,整数n)
{
整数合计=1;
for(int i=0;i
变量总计从0开始。因此调用
total=x*total
将始终为0


您需要将总计初始化为x。

公共静态整数功率(整数x,整数n)
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;


}
{ int total=1;//已将total初始化为1 对于(int i=0;i
而不是
i
你应该使用
i作为一个例子,看起来你的意思是:

if (n == 0) return 1;
检查电源,而不是基数


您也不是initialisign
total
,我认为使用
total=x
可以解决问题。

这里是一个具有log(n)复杂性而不是线性的解决方案。不过要小心溢出

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

初始化有许多正确答案。我也在做一些愚蠢的事情,因为我有一个;就在我的for行之后,没有人发现这个错误:-)。我在回答中发现并提到了这个错误,因为我在发布之前在eclipse中执行了它:)@Jeff:我确实捕捉到了,正如你所看到的,“;”没有出现在我发布的代码中。我只是不想明确提到你有一个额外的“;”@对不起!没有正确阅读。(这就是我的问题:—()。
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;
}