File tree Expand file tree Collapse file tree 2 files changed +51
-0
lines changed
0367-Valid_Perfect_Square Expand file tree Collapse file tree 2 files changed +51
-0
lines changed Original file line number Diff line number Diff line change 1+ // const num = 16;
2+ const num = 14 ;
3+
4+ function isPerfectSquare ( num : number ) : boolean {
5+ if ( num < 2 ) return true ;
6+
7+ let left = 2 ;
8+ let right = num >> 1 ;
9+ while ( left <= right ) {
10+ let mid = left + ( ( right - left ) >> 1 ) ;
11+ let div = num / mid ;
12+ if ( mid === div ) return true ;
13+ if ( mid < div ) {
14+ left = mid + 1 ;
15+ } else {
16+ right = mid - 1 ;
17+ }
18+ }
19+ return false ;
20+ }
21+
22+ console . time ( 'isPerfectSquare' ) ;
23+ isPerfectSquare ( num ) ;
24+ console . timeEnd ( 'isPerfectSquare' ) ;
25+
26+ let result = isPerfectSquare ( num ) ;
27+
28+ console . log ( result ) ;
Original file line number Diff line number Diff line change 1+ # 367. Valid Perfect Square
2+
3+ Given a positive integer num, return ` true ` <i >if ` num ` is a perfect square or</i > ` false ` otherwise.
4+
5+ <b >A perfect square</b > is an integer that is the square of an integer. In other words, it is the product of some integer with itself.
6+
7+ You must not use any built-in library function, such as ` sqrt ` .
8+
9+ ## Example 1:
10+
11+ > <span style =" color : white ;" >Input: </span >num = 16<br >
12+ > <span style =" color : white ;" >Output: </span >true<br >
13+ > <span style =" color : white ;" >Explanation: </span >We return true because 4 \* 4 = 16 and 4 is an integer.
14+
15+ ## Example 2:
16+
17+ > <span style =" color : white ;" >Input: </span >num = 14<br >
18+ > <span style =" color : white ;" >Output: </span >false<br >
19+ > <span style =" color : white ;" >Explanation: </span >We return false because 3.742 \* 3.742 = 14 and 3.742 is not an integer.
20+
21+ ## Constraints:
22+
23+ - 1 <= num <= 2<sup >31</sup > - 1
You can’t perform that action at this time.
0 commit comments