Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit f21e191

Browse files
committed
valid-perfect-square
1 parent f7b2015 commit f21e191

File tree

2 files changed

+52
-1
lines changed

2 files changed

+52
-1
lines changed

README.md

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,14 +7,17 @@
77
- 07:传递信息
88
- [src](https://github.com/rustors/leetcode/blob/main/src/bin/chuan-di-xin-xi.rs)
99
- [leetcode]((https://leetcode-cn.com/problems/chuan-di-xin-xi/))
10-
1110
- 09:用两个栈实现队列
1211
- [src](https://github.com/rustors/leetcode/blob/main/src/bin/yong-liang-ge-zhan-shi-xian-dui-lie-lcof.rs)
1312
- [leetcode](https://leetcode-cn.com/problems/yong-liang-ge-zhan-shi-xian-dui-lie-lcof/)
1413
- 229:求众数 II
1514
- [src](https://github.com/rustors/leetcode/blob/main/src/bin/majority-element-ii.rs)
1615
- [leetcode](https://leetcode-cn.com/problems/majority-element-ii/)
16+
- 367:有效的完全平方数
17+
- [src](https://github.com/rustors/leetcode/blob/main/src/bin/valid-perfect-square.rs)
18+
- [leetcode](https://leetcode-cn.com/problems/valid-perfect-square/)
1719
- 387:字符串中的第一个唯一字符
20+
1821
- [src](https://github.com/rustors/leetcode/blob/main/src/bin/first-unique-character-in-a-string.rs)
1922
- [leetcode](https://leetcode-cn.com/problems/first-unique-character-in-a-string/)
2023
- 746:检查整数及其两倍数是否存在

src/bin/valid-perfect-square.rs

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
fn main() {
2+
// assert_eq!(true, Solution::is_perfect_square(4), "4");
3+
// assert_eq!(false, Solution::is_perfect_square(5), "5");
4+
// assert_eq!(false, Solution::is_perfect_square(14), "14");
5+
// assert_eq!(true, Solution::is_perfect_square(16), "16");
6+
// assert_eq!(false, Solution::is_perfect_square(2147483647), "2147483647");
7+
assert_eq!(true, Solution::is_perfect_square(100000000), "100000000");
8+
}
9+
10+
11+
struct Solution;
12+
13+
impl Solution {
14+
// 使用二分的思维,
15+
// 从1开始尝试,
16+
// 当基数的平方小于num时,基数再次扩大2倍
17+
// 当基数的平凡大于num时,则基数处于当前基数与上一个基数之间,取中间数尝试
18+
// 当上一个基数与当前基数相等,且基数的平方不为num时,说明此数不是完全平方数,否则是完全平方数
19+
pub fn is_perfect_square(num: i32) -> bool {
20+
if num == 1 && num == 0 {
21+
return true;
22+
}
23+
24+
let mut num1 = 1;
25+
let mut last_num = 1;
26+
27+
loop {
28+
if num / num1 == num1 {
29+
return if num % num1 == 0 {
30+
true
31+
} else {
32+
false
33+
};
34+
} else if num / num1 > num1 {
35+
last_num = num1;
36+
num1 *= 2;
37+
} else {
38+
num1 = (last_num + num1) / 2;
39+
}
40+
41+
if num1 == last_num && num / num1 != num1 {
42+
return false;
43+
}
44+
}
45+
46+
false
47+
}
48+
}

0 commit comments

Comments
 (0)