开发者

Calculate the power of 2, java

I want to calculate the power of 2 using recursion. Here is my code:

class Aufg1{
    public static void main(String args[]){
        int erg = zweiHochPositiv(10);
    }

    public static int zweiHochPositiv(int exponent){
        if(exponent > 0)
            return (2*zweiHochPositiv(exponent--));
        else
        开发者_Python百科    return 1;
    }
}

I get a lot of errors at

return (2*zweiHochPositiv(exponent--));

but I have no idea what may be wrong.


Replace

return (2*zweiHochPositiv(exponent--));

with

return (2*zweiHochPositiv(exponent - 1));

exponent-- evaluates to the value of the exponent variable and then decrements it. So when you call zweiHochPositiv(1), the method will call zweiHochPositiv(1) again.

As a result, this method, when called with a value > 0, will recurse indefinitely and ultimately overflow the stack.


You need to use prefix version of --.

This should work:

return (2*zweiHochPositiv(--exponent));

Explanation: exponent-- will never actually lower exponent's value, so you're calling your recursive function every time with the same value, and that will blow your stack.

--exponent will lower it's value by one, so you should get desired behaviour.


I think an efficient way of doing it would be to use the binary representation property of a "power of 2" - its just a bit shift of 1, "exponent" number of times.

Hence, 2^2 = 1 << 2 = (in binary) ....0000 0100 = 4


return (2*zweiHochPositiv(--exponent));

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜