Skip to content

Commit e34ca9d

Browse files
committed
feat: add rust solution to lc problem: No.0367
No.0367.Valid Perfect Square
1 parent 234a66b commit e34ca9d

File tree

3 files changed

+90
-0
lines changed

3 files changed

+90
-0
lines changed

solution/0300-0399/0367.Valid Perfect Square/README.md

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -159,6 +159,42 @@ func isPerfectSquare(num int) bool {
159159
}
160160
```
161161

162+
### **Rust**
163+
164+
```rust
165+
use std::cmp::Ordering;
166+
167+
impl Solution {
168+
pub fn is_perfect_square(mut num: i32) -> bool {
169+
let num: i64 = num as i64;
170+
let mut l = 0;
171+
let mut r = num;
172+
while l < r {
173+
let mid = l + (r - l) / 2;
174+
match (mid * mid).cmp(&num) {
175+
Ordering::Less => l = mid + 1,
176+
Ordering::Greater => r = mid - 1,
177+
Ordering::Equal => return true,
178+
}
179+
}
180+
r * r == num
181+
}
182+
}
183+
```
184+
185+
```rust
186+
impl Solution {
187+
pub fn is_perfect_square(mut num: i32) -> bool {
188+
let mut i = 1;
189+
while num > 0 {
190+
num -= i;
191+
i += 2;
192+
}
193+
num == 0
194+
}
195+
}
196+
```
197+
162198
### **...**
163199

164200
```

solution/0300-0399/0367.Valid Perfect Square/README_EN.md

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,42 @@ func isPerfectSquare(num int) bool {
136136
}
137137
```
138138

139+
### **Rust**
140+
141+
```rust
142+
use std::cmp::Ordering;
143+
144+
impl Solution {
145+
pub fn is_perfect_square(mut num: i32) -> bool {
146+
let num: i64 = num as i64;
147+
let mut l = 0;
148+
let mut r = num;
149+
while l < r {
150+
let mid = l + (r - l) / 2;
151+
match (mid * mid).cmp(&num) {
152+
Ordering::Less => l = mid + 1,
153+
Ordering::Greater => r = mid - 1,
154+
Ordering::Equal => return true,
155+
}
156+
}
157+
r * r == num
158+
}
159+
}
160+
```
161+
162+
```rust
163+
impl Solution {
164+
pub fn is_perfect_square(mut num: i32) -> bool {
165+
let mut i = 1;
166+
while num > 0 {
167+
num -= i;
168+
i += 2;
169+
}
170+
num == 0
171+
}
172+
}
173+
```
174+
139175
### **...**
140176

141177
```
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
use std::cmp::Ordering;
2+
3+
impl Solution {
4+
pub fn is_perfect_square(mut num: i32) -> bool {
5+
let num: i64 = num as i64;
6+
let mut l = 0;
7+
let mut r = num;
8+
while l < r {
9+
let mid = l + (r - l) / 2;
10+
match (mid * mid).cmp(&num) {
11+
Ordering::Less => l = mid + 1,
12+
Ordering::Greater => r = mid - 1,
13+
Ordering::Equal => return true,
14+
}
15+
}
16+
r * r == num
17+
}
18+
}

0 commit comments

Comments
 (0)