🚀Day 09/180 (Math) 50. Pow(x, n)(Leetcode)
#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.0n = 10ans = 1.0
Iteration Details
First Iteration:
Current
nvalue: 10 (even)xsquared: ( x = 2.0 \times 2.0 = 4.0 )nright-shifted: ( n = 10 >> 1 = 5 )ansremains: ( ans = 1.0 )
Second Iteration:
Current
nvalue: 5 (odd)Update
ans: ( ans = 1.0 \times 4.0 = 4.0 )xsquared: ( x = 4.0 \times 4.0 = 16.0 )nright-shifted: ( n = 5 >> 1 = 2 )Updated
ans: ( ans = 4.0 )
Third Iteration:
Current
nvalue: 2 (even)xsquared: ( x = 16.0 \times 16.0 = 256.0 )nright-shifted: ( n = 2 >> 1 = 1 )ansremains: ( ans = 4.0 )
Fourth Iteration:
Current
nvalue: 1 (odd)Update
ans: ( ans = 4.0 \times 256.0 = 1024.0 )xsquared: ( x = 256.0 \times 256.0 = 65536.0 )nright-shifted: ( n = 1 >> 1 = 0 )Updated
ans: ( ans = 1024.0 )
End of Loop:
Current
nvalue: 0Exit the loop
Final Output
ans = 1024.0
Therefore, the function correctly calculates ( 2^{10} = 1024.0 ).