-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path69.x-的平方根.php
74 lines (69 loc) · 1.27 KB
/
69.x-的平方根.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
<?php
/*
* @lc app=leetcode.cn id=69 lang=php
*
* [69] x 的平方根
*
* https://leetcode-cn.com/problems/sqrtx/description/
*
* algorithms
* Easy (39.20%)
* Likes: 675
* Dislikes: 0
* Total Accepted: 306.1K
* Total Submissions: 780.3K
* Testcase Example: '4'
*
* 实现 int sqrt(int x) 函数。
*
* 计算并返回 x 的平方根,其中 x 是非负整数。
*
* 由于返回类型是整数,结果只保留整数的部分,小数部分将被舍去。
*
* 示例 1:
*
* 输入: 4
* 输出: 2
*
*
* 示例 2:
*
* 输入: 8
* 输出: 2
* 说明: 8 的平方根是 2.82842...,
* 由于返回类型是整数,小数部分将被舍去。
*
*
*/
// @lc code=start
class Solution
{
// /**
// * @param int $x
// * @return int
// */
// public function mySqrt($x)
// {
// // system method
// return (int)sqrt($x);
// }
/**
* @param int $x
* @return int
*/
public function mySqrt($x)
{
if ($x === 2) {
return 1;
}
for ($i = 1; $i < $x; $i++) {
if ($i * $i === $x) {
return $i;
} elseif ($i * $i > $x) {
return $i - 1;
}
}
return $x;
}
}
// @lc code=end