-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsqrt.cpp
More file actions
59 lines (56 loc) · 1.25 KB
/
sqrt.cpp
File metadata and controls
59 lines (56 loc) · 1.25 KB
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
// =====================================================================================
//
// Filename: sqrt.cpp
//
// Description: 69. Sqrt(x)
//
// Version: 1.0
// Created: 11/05/2019 07:10:15 PM
// Revision: none
// Compiler: g++
//
// Author: Zhu Xianfeng (), xianfeng.zhu@gmail.com
// Organization:
//
// =====================================================================================
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
class Solution
{
public:
int mySqrt(int x)
{
int left = 1;
int right = x;
while (left < right)
{
int mid = ((uint64_t)left + right) / 2;
uint64_t val = (uint64_t)mid * mid;
if (val > x)
{
right = mid - 1;
}
else if (val < x)
{
left = mid + 1;
}
else
{
return mid;
}
}
return (((uint64_t)left * left) <= x ? left : (left - 1));
}
};
int main(int argc, char* argv[])
{
int x = 10;
if (argc > 1)
{
x = atoi(argv[1]);
}
int val = Solution().mySqrt(x);
printf("sqrt(%d) = %d\n", x, val);
return 0;
}