In this tutorial, we are going to solve a leetcode problem, Pow(x, n)
Implement pow(x, n), which calculates x raised to the power n (i.e., xn).
Input: x = 2.00000, n = 10
Output: 1024.00000
Input: x = 2.10000, n = 3
Output: 9.26100
Input: x = 2.00000, n = -2
Output: 0.25000
Explanation: 2-2 = 1/22 = 1/4 = 0.25
class Solution(object):
def myPow(self, x, n):
if n >= 0:
return self.helper(x, n)
else:
return 1 / self.helper(x, -n)
def helper(self, x, n):
if n == 0:
return 1
else:
if n % 2 == 0:
return self.myPow(x * x, n/2)
else:
return x * self.myPow(x * x, (n-1)/2)
step1: In this problem, we will be using recursion to approach this problem.
step2: Now, here we will be using the helper function to deal will the +ve and -ve values of n.
step3: Then, we call the helper function from myPow function and inside the helper function we decrease the value of n & multiplying the x recursively.
step4: After we reached the base condition we recursively return the result.
Trainings :
Data Science Training in Indore | Python Training in Indore | Data Analytics Training in Indore | Blockchain Training in Indore | React JS Training in Indore | Web Development Training in Indore | Full Stack Development Training in Indore |Free Courses and Resource :
Dart | OpenCV Tutorials | Projects | Interview Questions | Python Data Structures and Algorithms | Aptitude Tests | Verbal Aptitude | Matplotlib Tutorials | Examples | Interview Questions | HackerRank Python | Pandas Tutorials | Projects | Interview Questions | Rust Tutorials | Projects | Interview Questions | ExpressJS Tutorials | Projects | Interview Questions | Django | MongoDB Tutorials | Examples | Interview Questions | HackerRank C Program Solutions | Python Tutorials by CodersDaily | React.js Tutorials | Golang Tutorials | Projects | Interview Questions | MS Sql Server Tutorials | Examples | Interview Questions | Verbal Ability Tutorial | Numpy Tutorials | Projects | Interview Questions | Power BI Tutorials | Projects | Interview Questions | Example Dashboards | Tensor Flow | HackerRank C++ Solutions | Django REST Framework Tutorial | CodeChef Python Solutions | Leetcode Python Solutions | Reasoning Ability Tutorial | Quantitative Ability Tutorial | C++ Tutorials | HackerRank Java Solutions | TCS NQT Mock Test Series | Verbal Aptitude 2 | HackerRank DSA Solutions | HackerRank SQL Solutions | Javascript | Node.js Tutorials |Interview Questions :
Pandas Tutorials | Projects | Interview Questions | ExpressJS Tutorials | Projects | Interview Questions | Django | Python Tutorials by CodersDaily | Golang Tutorials | Projects | Interview Questions | Numpy Tutorials | Projects | Interview Questions | Django REST Framework Tutorial |Top Colleges in India :
Indian Institute of Technology Bombay | Jaypee University of Engineering and Technology - Guna |