Skip to content

Comments

[367] Valid Perfect Square#151

Open
limHyeonTaek wants to merge 1 commit intomainfrom
hyeontaek/ValidPerfectSquare
Open

[367] Valid Perfect Square#151
limHyeonTaek wants to merge 1 commit intomainfrom
hyeontaek/ValidPerfectSquare

Conversation

@limHyeonTaek
Copy link
Collaborator

[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

Input: num = 16
Output: true
Explanation: We return true because 4 * 4 = 16 and 4 is an integer.

코드 설명

public static boolean isPerfectSquare(int num) {
  if (num < 2) {
    return true;
  }
  long left = 2, right = num / 2, mid, square;
  while (left <= right) {
    mid = left + (right - left) / 2;
    square = mid * mid;
    if (square == num) {
      return true;
    } else if (square > num) {
      right = mid - 1;
    } else {
      left = mid + 1;
    }
  }
  return false;
}

if (num < 2) { return true; }
0과 1은 완전 제곱수이므로 true를 반환합니다.

long left = 2, right = num / 2, mid, square;
이진 검색을 위한 초기 범위를 설정합니다. left는 2, right는 num의 절반으로 초기화합니다.

while (left <= right) { ... }
이진 검색을 수행합니다.

mid = left + (right - left) / 2;
현재 범위의 중간 값을 계산합니다.

square = mid * mid;
중간 값의 제곱을 계산합니다.

if (square == num) { return true; }
제곱이 num과 같으면 true를 반환합니다.

else if (square > num) { right = mid - 1; }
제곱이 num보다 크면 범위를 왼쪽으로 좁힙니다.

@limHyeonTaek limHyeonTaek added the coding test 코딩테스트 라벨 label Jun 28, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

coding test 코딩테스트 라벨

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant