File tree Expand file tree Collapse file tree 2 files changed +52
-1
lines changed Expand file tree Collapse file tree 2 files changed +52
-1
lines changed Original file line number Diff line number Diff line change 7
7
- 07:传递信息
8
8
- [ src] ( https://github.com/rustors/leetcode/blob/main/src/bin/chuan-di-xin-xi.rs )
9
9
- [ leetcode] ( (https://leetcode-cn.com/problems/chuan-di-xin-xi/) )
10
-
11
10
- 09:用两个栈实现队列
12
11
- [ src] ( https://github.com/rustors/leetcode/blob/main/src/bin/yong-liang-ge-zhan-shi-xian-dui-lie-lcof.rs )
13
12
- [ leetcode] ( https://leetcode-cn.com/problems/yong-liang-ge-zhan-shi-xian-dui-lie-lcof/ )
14
13
- 229:求众数 II
15
14
- [ src] ( https://github.com/rustors/leetcode/blob/main/src/bin/majority-element-ii.rs )
16
15
- [ 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/ )
17
19
- 387:字符串中的第一个唯一字符
20
+
18
21
- [ src] ( https://github.com/rustors/leetcode/blob/main/src/bin/first-unique-character-in-a-string.rs )
19
22
- [ leetcode] ( https://leetcode-cn.com/problems/first-unique-character-in-a-string/ )
20
23
- 746:检查整数及其两倍数是否存在
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments