Why do i get a wrong answer?


  • 0
    B
    class Solution {
    public:
        double pow(double x, int n) {
        int flag = 0;
        double product = x;
        if(n == 0) return 1;
        if(n < 0){
            flag = 1;
            n = -n;
        }
        
        while(n != -1 && n != 1 ){
            product *= product;
            if(n % 2 == 1) product *= x; 
            n /= 2;
        }
        if(flag == 1 && x != 0 )return (1.0 / product);
        else return product;
       }
    };
    

    Input: 8.84372, -5

    Output: 0.00000

    Expected: 0.00002


  • 0
    K

    Because your logic for calculating power is wrong try to print result of power(2,5).


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.