| | 1 | | // -------------------------------------------------------------------------------- |
| | 2 | | // Copyright (C) 2025 Eugene Eremeev (also known as Yevhenii Yeriemeieiv). |
| | 3 | | // All Rights Reserved. |
| | 4 | | // -------------------------------------------------------------------------------- |
| | 5 | | // This software is the confidential and proprietary information of Eugene Eremeev |
| | 6 | | // (also known as Yevhenii Yeriemeieiv) ("Confidential Information"). You shall not |
| | 7 | | // disclose such Confidential Information and shall use it only in accordance with |
| | 8 | | // the terms of the license agreement you entered into with Eugene Eremeev (also |
| | 9 | | // known as Yevhenii Yeriemeieiv). |
| | 10 | | // -------------------------------------------------------------------------------- |
| | 11 | |
|
| | 12 | | namespace LeetCode.Algorithms.ValidPerfectSquare; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class ValidPerfectSquareBinarySearch : IValidPerfectSquare |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(log n) |
| | 19 | | /// Space complexity - O(1) |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="num"></param> |
| | 22 | | /// <returns></returns> |
| | 23 | | public bool IsPerfectSquare(int num) |
| 3 | 24 | | { |
| 3 | 25 | | long left = 1; |
| 3 | 26 | | long right = num; |
| | 27 | |
|
| 39 | 28 | | while (left <= right) |
| 37 | 29 | | { |
| 37 | 30 | | var mid = left + ((right - left) / 2); |
| | 31 | |
|
| 37 | 32 | | var sqrt = mid * mid; |
| | 33 | |
|
| 37 | 34 | | if (sqrt == num) |
| 1 | 35 | | { |
| 1 | 36 | | return true; |
| | 37 | | } |
| | 38 | |
|
| 36 | 39 | | if (sqrt < num) |
| 7 | 40 | | { |
| 7 | 41 | | left = mid + 1; |
| 7 | 42 | | } |
| | 43 | | else |
| 29 | 44 | | { |
| 29 | 45 | | right = mid - 1; |
| 29 | 46 | | } |
| 36 | 47 | | } |
| | 48 | |
|
| 2 | 49 | | return false; |
| 3 | 50 | | } |
| | 51 | | } |