일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
- axios
- react-router
- react-redux
- 항해99
- Algorithm
- redux-saga
- 테코테코
- 코딩테스트합격자되기
- 항해플러스
- createSlice
- sw expert academy
- maeil-mail
- react
- 리액트
- C++
- java
- programmers
- 매일메일
- redux-toolkit
- 자바
- json-server
- Python
- 이코테
- 프로그래머스
- JavaScript
- redux
- Get
- 알고리즘
- useDispatch
- SW
- Today
- Total
Binary Journey
[프로그래머스] 정수 제곱근 판별 본문
출처: 프로그래머스 코딩 테스트 연습, https://programmers.co.kr/learn/challenges
문제는 이렇다.
** Javascript
내 풀이는 이렇다.
function solution(n) {
const sqrt = Math.sqrt(n) % 1 === 0 ? Math.sqrt(n) : -1;
return sqrt === -1 ? sqrt : Math.pow(sqrt + 1, 2);
}
사실 온전한 내 실력으로 풀지는 않았고 루트를 씌웠을 때 결과값이 정수인지 아닌지 가리는 방법을 갓택오버플로우에서 찾았다.
위 주소에서
var isSquare = function (n) {
return Math.sqrt(n) % 1 === 0;
};
이 식을 활용했다. 루트 씌운 값을 1로 나눴을 때도 나머지가 없는 경우를 골라내는 것이다.
javascript 에서 Math.sqrt(숫자) 는 숫자에 루트를 씌운 것이고
Math.pow(숫자, 지수) 는 숫자^지수 이다.
(2021-08-09 추가)
** Java
import java.lang.Math;
class Solution {
public long solution(double n) {
double sqrt = Math.sqrt(n);
return (sqrt - Math.floor(sqrt)) == 0 ? (long) Math.pow(sqrt + 1, 2) : -1;
}
}
Java 의 경우 perfect square root 를 찾는 방법을 구글링 해봤더니 아래 방법을 쓰는 방법이 나왔다
static boolean checkPerfectSquare(double x)
{
// finding the square root of given number
double sq = Math.sqrt(x);
/* Math.floor() returns closest integer value, for
* example Math.floor of 984.1 is 984, so if the value
* of sq is non integer than the below expression would
* be non-zero.
*/
return ((sq - Math.floor(sq)) == 0);
}
출처: https://beginnersbook.com/2019/02/java-program-to-check-if-given-number-is-perfect-square/
Math.sqrt() 와 Math.power() 의 경우 return 타입이 double 이므로 주의해야 한다.
추천을 가장 많이 받은 풀이는 아래와 같다.
class Solution {
public long solution(long n) {
if (Math.pow((int)Math.sqrt(n), 2) == n) {
return (long) Math.pow(Math.sqrt(n) + 1, 2);
}
return -1;
}
}
두 번째로 추천을 많이 받은 풀이인데 이게 가장 내 취향에 맞다.
class Solution {
public long solution(long n) {
double i = Math.sqrt(n);
return Math.floor(i) == i ? (long) Math.pow(i + 1, 2) : -1;
}
}
** Python
그래서 파이썬은 취향에 맞는 풀이로 작성해 보았다.
import math
def solution(n):
sqrt = math.sqrt(n)
return math.pow(sqrt + 1, 2) if math.floor(sqrt) == sqrt else -1
언어마다 추천을 가장 많이 받은 풀이를 찾아보면 재밌다. 상상도 못한 풀이 방법을 발견할 수 있다.
def nextSqure(n):
sqrt = n ** (1/2)
if sqrt % 1 == 0:
return (sqrt + 1) ** 2
return 'no'
생각해보면 1/2 제곱이 루트인데 굳이 javascript 나 java나 python이나 math 를 이용할 필요가 있었나 싶다.
허탈하다.
'프로그래머스 > level 1' 카테고리의 다른 글
[프로그래머스] 핸드폰 번호 가리기 (0) | 2021.07.23 |
---|---|
[프로그래머스] 행렬의 덧셈 (0) | 2021.07.23 |
[프로그래머스] 숫자 문자열과 영단어 (0) | 2021.07.21 |
[프로그래머스] 문자열 내림차순으로 배치하기 (0) | 2021.07.21 |
[프로그래머스] 문자열 내 마음대로 정렬하기 (0) | 2021.07.21 |