-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalid_perfect_square.cpp
More file actions
62 lines (58 loc) · 1.47 KB
/
valid_perfect_square.cpp
File metadata and controls
62 lines (58 loc) · 1.47 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
60
61
62
// =====================================================================================
//
// Filename: valid_perfect_square.cpp
//
// Description: 367. Valid Perfect Square.
// Given a positive integer num, write a function which returns True if
// num is a perfect square else False.
//
// Version: 1.0
// Created: 11/08/2019 04:10:37 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:
bool isPerfectSquare(int num)
{
int left = 1;
int right = num;
while (left <= right)
{
uint64_t mid = ((uint64_t)left + right) / 2;
uint64_t square = mid * mid;
if (square > num)
{
right = mid - 1;
}
else if (square < num)
{
left = mid + 1;
}
else
{
return true;
}
}
return false;
}
};
int main(int argc, char* argv[])
{
int num = 2147483647; // INT_MAX
if (argc > 1)
{
num = atoi(argv[1]);
}
bool valid = Solution().isPerfectSquare(num);
printf("Is perfect square, %d? %s\n", num, (valid ? "Yes" : "No"));
return 0;
}