From 352411be9b1abeebaf7983c45ad1968af47b74a0 Mon Sep 17 00:00:00 2001 From: Levy Date: Fri, 10 May 2024 14:30:41 +0800 Subject: [PATCH] 0367: Valid Perfect Square --- 0367-Valid_Perfect_Square/main.ts | 28 ++++++++++++++++++++++++++++ 0367-Valid_Perfect_Square/readme.md | 23 +++++++++++++++++++++++ 2 files changed, 51 insertions(+) create mode 100644 0367-Valid_Perfect_Square/main.ts create mode 100644 0367-Valid_Perfect_Square/readme.md diff --git a/0367-Valid_Perfect_Square/main.ts b/0367-Valid_Perfect_Square/main.ts new file mode 100644 index 0000000..3a09ea2 --- /dev/null +++ b/0367-Valid_Perfect_Square/main.ts @@ -0,0 +1,28 @@ +// const num = 16; +const num = 14; + +function isPerfectSquare(num: number): boolean { + if (num < 2) return true; + + let left = 2; + let right = num >> 1; + while (left <= right) { + let mid = left + ((right - left) >> 1); + let div = num / mid; + if (mid === div) return true; + if (mid < div) { + left = mid + 1; + } else { + right = mid - 1; + } + } + return false; +} + +console.time('isPerfectSquare'); +isPerfectSquare(num); +console.timeEnd('isPerfectSquare'); + +let result = isPerfectSquare(num); + +console.log(result); diff --git a/0367-Valid_Perfect_Square/readme.md b/0367-Valid_Perfect_Square/readme.md new file mode 100644 index 0000000..d48f8cd --- /dev/null +++ b/0367-Valid_Perfect_Square/readme.md @@ -0,0 +1,23 @@ +# 367. Valid Perfect Square + +Given a positive integer num, return `true` if `num` is a perfect square or `false` otherwise. + +A perfect square is an integer that is the square of an integer. In other words, it is the product of some integer with itself. + +You must not use any built-in library function, such as `sqrt`. + +## Example 1: + +> Input: num = 16
+> Output: true
+> Explanation: We return true because 4 \* 4 = 16 and 4 is an integer. + +## Example 2: + +> Input: num = 14
+> Output: false
+> Explanation: We return false because 3.742 \* 3.742 = 14 and 3.742 is not an integer. + +## Constraints: + +- 1 <= num <= 231 - 1