[알고리즘문제풀기] 제곱수 판별하기

silver's avatar
Dec 07, 2024
[알고리즘문제풀기] 제곱수 판별하기

문제

 

정답

class Solution { public int solution(int n) { int answer = 0; double a = Math.sqrt(n); if(a == (int)a){ answer = 1; } else{ answer = 2; } return answer; } }
 

streamAPI

이 문제엔 비효율적
import java.util.stream.IntStream; class Solution { public int solution(int n) { //0부터 n의 제곱근까지의 정수를 스트림으로 생성 return IntStream.rangeClosed(0, (int)Math.sqrt(n)) //각 정수 i에 대해 i의 제곱이 n과 같은지 필터링 .filter(i -> i * i == n) //조건을 만족하는 요소가 있으면 해당 요소를 반환 .findAny() //조건을 만족하는 요소있으면 1 없으면 2 반환 .isPresent() ? 1 : 2; } }
 

다른 사람들이 작성한 정답

class Solution { public int solution(int n) { int answer = 0; return Math.sqrt(n) % 1 == 0 ? 1 : 2; } }
 
Share article

silver