Skip to main content

Command Palette

Search for a command to run...

🚀Day 09/180 (Math) 50. Pow(x, n)(Leetcode)

Published
•2 min read•View as Markdown

50. Pow(x, n)

#180DaysOfDSA#DailyCodingChallenge #LeetCodeJourney #GeeksforGeeks #CodingNinjas #Codechef #CodeForces #ContinuousLearning #TechCommunity

class Solution {
public:
    double myPow(double x, int n) {
        double ans = 1.0;
        if(n == 0 || x == 1) return 1;
        else if (x == 0  ) return 0;
        if(n<0)
        {
            x= 1/x;
            if(n == INT_MIN){
                n= INT_MAX;
                ans *= x;
            }
            else
                n = n *(-1);
        }
        while(n>0){
            if((n&1)==1)
                ans *=x;
            x*=x;
            n>>=1;
        }
        return ans;
        }
};

Let's perform a detailed dry run for x = 2.0 and n = 10.

Initial Setup

  • x = 2.0

  • n = 10

  • ans = 1.0

Iteration Details

  1. First Iteration:

    • Current n value: 10 (even)

    • x squared: ( x = 2.0 \times 2.0 = 4.0 )

    • n right-shifted: ( n = 10 >> 1 = 5 )

    • ans remains: ( ans = 1.0 )

  2. Second Iteration:

    • Current n value: 5 (odd)

    • Update ans: ( ans = 1.0 \times 4.0 = 4.0 )

    • x squared: ( x = 4.0 \times 4.0 = 16.0 )

    • n right-shifted: ( n = 5 >> 1 = 2 )

    • Updated ans: ( ans = 4.0 )

  3. Third Iteration:

    • Current n value: 2 (even)

    • x squared: ( x = 16.0 \times 16.0 = 256.0 )

    • n right-shifted: ( n = 2 >> 1 = 1 )

    • ans remains: ( ans = 4.0 )

  4. Fourth Iteration:

    • Current n value: 1 (odd)

    • Update ans: ( ans = 4.0 \times 256.0 = 1024.0 )

    • x squared: ( x = 256.0 \times 256.0 = 65536.0 )

    • n right-shifted: ( n = 1 >> 1 = 0 )

    • Updated ans: ( ans = 1024.0 )

  5. End of Loop:

    • Current n value: 0

    • Exit the loop

Final Output

  • ans = 1024.0

Therefore, the function correctly calculates ( 2^{10} = 1024.0 ).

More from this blog

CodeCrafters

22 posts