-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPow(n,x).py
More file actions
43 lines (36 loc) · 1.25 KB
/
Pow(n,x).py
File metadata and controls
43 lines (36 loc) · 1.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# Question link - https://leetcode.com/problems/powx-n/description/?envType=study-plan-v2&envId=top-interview-150
class Solution(object):
def myPow(self, x, n):
"""
:type x: float
:type n: int
:rtype: float
"""
# Sol2 :O(logN)
# Using the recursive function , with divide and conquer concepts
def helper(x , n):
# Basecase
if x == 0: return 0
if n == 0 : return 1
# recursive call , by multipying itself
res = helper(x * x , n // 2)
# return the result if n is even , otherwise
return x * res if n % 2 else res
# Function call
res = helper(x , abs(n))
# Return the res if +ve n or else return 1 / res if -ve n
return res if n >= 0 else 1 / res
# Sol1
# if n == 0:
# return 1.0
# elif n < 0:
# x = 1 / x
# n = -n
# result = 1.0
# current_product = x
# while n > 0:
# if n % 2 == 1: # If n is odd
# result *= current_product
# current_product *= current_product # Square the base
# n //= 2 # Divide n by 2
# return result