File tree Expand file tree Collapse file tree 1 file changed +65
-0
lines changed Expand file tree Collapse file tree 1 file changed +65
-0
lines changed Original file line number Diff line number Diff line change 1+ /*
2+ * @lc app=leetcode id=50 lang=java
3+ *
4+ * [50] Pow(x, n)
5+ *
6+ * https://leetcode.com/problems/powx-n/description/
7+ *
8+ * algorithms
9+ * Medium (27.87%)
10+ * Likes: 916
11+ * Dislikes: 2236
12+ * Total Accepted: 343.5K
13+ * Total Submissions: 1.2M
14+ * Testcase Example: '2.00000\n10'
15+ *
16+ * Implement pow(x, n), which calculates x raised to the power n (x^n).
17+ *
18+ * Example 1:
19+ *
20+ *
21+ * Input: 2.00000, 10
22+ * Output: 1024.00000
23+ *
24+ *
25+ * Example 2:
26+ *
27+ *
28+ * Input: 2.10000, 3
29+ * Output: 9.26100
30+ *
31+ *
32+ * Example 3:
33+ *
34+ *
35+ * Input: 2.00000, -2
36+ * Output: 0.25000
37+ * Explanation: 2^-2 = 1/2^2 = 1/4 = 0.25
38+ *
39+ *
40+ * Note:
41+ *
42+ *
43+ * -100.0 < x < 100.0
44+ * n is a 32-bit signed integer, within the range [−2^31, 2^31 − 1]
45+ *
46+ *
47+ */
48+ class Solution {
49+ public double myPow (double x , int n ) {
50+ if (n == 0 ) {
51+ return 1 ;
52+ }
53+ double t = myPow (x , n /2 );
54+ if (n % 2 != 0 ) {
55+ if (n < 0 ) {
56+ return t * t / x ;
57+ } else {
58+ return t * t * x ;
59+ }
60+ } else {
61+ return t * t ;
62+ }
63+ }
64+ }
65+
You can’t perform that action at this time.
0 commit comments