简体   繁体   中英

Making a pow(x1, x2) function using only increments, decrements, loops, and =0

Those are the constraints of my problem --- I'm trying to solve this using another computational method, but trying to solve it in Java first. I can read other languages.

This is what I have so far:

public static int pow(int x1, int x2){
    if(x1 == 0) return 0;
    if(x2 == 0) return 1;
    int exp = x2;
    int y = x1;
    exp--;
    int multi = x1;

    while(exp != 0) {
        int temp = y;
        while(multi !=0) {
            while (temp != 0) {
                y++;
                temp--;
            }
            multi--;
        }
        exp --;
        multi = x1;
        System.out.println();
    }

    return y;
}

pow(4,4) should be 256 , but I'm getting 32 . pow(5,4) should be 625 , but I'm getting 40 .

I tried to get the correct result changing your implementation as little as possible (since it was almost correct!).

Essentially you needed to reuse in the inner while loop the y value you had assigned to temp. I added the variable loopTempY for this purpose.

Another minor change was to the external loop, you only need to loop to greater than 1.

public static int pow(int x1, int x2) {
    if (x1 == 0) return 0;
    if (x2 == 0) return 1;
    int exp = x2;
    int y = x1;
    int multi;

    while (exp > 1) {
        multi = x1;
        int temp = y;
        int loopTempY = temp;
        while (multi != 1) {
            while (temp != 0) {
                y++;
                temp--;
            }
            temp = loopTempY;
            multi--;
        }
        exp--;

        System.out.println(y);
    }

    return y;
}  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM