- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0069-sqrtx.cpp
33 lines (28 loc) · 708 Bytes
/
0069-sqrtx.cpp
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
/*
69. Sqrt(x)
Submitted: February 23, 2025
Runtime: 0 ms (beats 100.00%
Memory: 8.58 MB (beats 51.10%)
*/
// fast inverse square root
doubleQ_rsqrt( double number )
{
long i;
double x2, y;
constdouble threehalfs = 1.5;
x2 = number * 0.5;
y = number;
i = * ( long * ) &y;
i = 0x5fe6eb50c7b537a9 - ( i >> 1 );
y = * ( double * ) &i;
y = y * ( threehalfs - ( x2 * y * y ) ); // 1st iteration
y = y * ( threehalfs - ( x2 * y * y ) ); // 2nd iteration, this can be removed
y = y * ( threehalfs - ( x2 * y * y ) ); // added in 3rd iteration so we can pass leetcode testcases
return y;
}
classSolution {
public:
intmySqrt(int x) {
return1.0 / Q_rsqrt(x);
}
};