Skip to content

Commit 4f5b102

Browse files
authored
feat: add rust solution to lc problem: No.0050 (#1292)
1 parent dd0c138 commit 4f5b102

File tree

3 files changed

+88
-0
lines changed

3 files changed

+88
-0
lines changed

solution/0000-0099/0050.Pow(x, n)/README.md

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,37 @@ public:
124124
};
125125
```
126126

127+
### **Rust**
128+
129+
```rust
130+
impl Solution {
131+
#[allow(dead_code)]
132+
pub fn my_pow(x: f64, n: i32) -> f64 {
133+
let mut x = x;
134+
let n = n as i64;
135+
if n >= 0 {
136+
Self::quick_pow(&mut x, n)
137+
} else {
138+
1.0 / Self::quick_pow(&mut x, -n)
139+
}
140+
}
141+
142+
#[allow(dead_code)]
143+
fn quick_pow(x: &mut f64, mut n: i64) -> f64 {
144+
// `n` should greater or equal to zero
145+
let mut ret = 1.0;
146+
while n != 0 {
147+
if n & 0x1 == 1 {
148+
ret *= *x;
149+
}
150+
*x *= *x;
151+
n >>= 1;
152+
}
153+
ret
154+
}
155+
}
156+
```
157+
127158
### **Go**
128159

129160
```go

solution/0000-0099/0050.Pow(x, n)/README_EN.md

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,37 @@ public:
108108
};
109109
```
110110

111+
### **Rust**
112+
113+
```rust
114+
impl Solution {
115+
#[allow(dead_code)]
116+
pub fn my_pow(x: f64, n: i32) -> f64 {
117+
let mut x = x;
118+
let n = n as i64;
119+
if n >= 0 {
120+
Self::quick_pow(&mut x, n)
121+
} else {
122+
1.0 / Self::quick_pow(&mut x, -n)
123+
}
124+
}
125+
126+
#[allow(dead_code)]
127+
fn quick_pow(x: &mut f64, mut n: i64) -> f64 {
128+
// `n` should greater or equal to zero
129+
let mut ret = 1.0;
130+
while n != 0 {
131+
if n & 0x1 == 1 {
132+
ret *= *x;
133+
}
134+
*x *= *x;
135+
n >>= 1;
136+
}
137+
ret
138+
}
139+
}
140+
```
141+
111142
### **Go**
112143

113144
```go
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
impl Solution {
2+
#[allow(dead_code)]
3+
pub fn my_pow(x: f64, n: i32) -> f64 {
4+
let mut x = x;
5+
let n = n as i64;
6+
if n >= 0 {
7+
Self::quick_pow(&mut x, n)
8+
} else {
9+
1.0 / Self::quick_pow(&mut x, -n)
10+
}
11+
}
12+
13+
#[allow(dead_code)]
14+
fn quick_pow(x: &mut f64, mut n: i64) -> f64 {
15+
// `n` should greater or equal to zero
16+
let mut ret = 1.0;
17+
while n != 0 {
18+
if n & 0x1 == 1 {
19+
ret *= *x;
20+
}
21+
*x *= *x;
22+
n >>= 1;
23+
}
24+
ret
25+
}
26+
}

0 commit comments

Comments
 (0)