NumberFun
xFYou might know some pretty large perfect squares. But what about the NEXT one?Complete the findNextSquare method that finds the next integral perfect square after the one passed as a parameter. Recall that an integral perfect square is an integer n such that sqrt(n) is also an integer.If the parameter is itself not a perfect square, than -1 should be returned. You may assume the parameter is positive.Examples:findNextSquare(121) --> returns 144findNextSquare(625) --> returns 676findNextSquare(114) --> returns -1 since 114 is not a perfect
정사각형 넓이가 주어지고, 그 다음 큰 정사각형 넓이를 구하는 문제다. 만약 주어진 파라미터 값에 대응하는 정사각형이 없을 경우, -1을 리턴하면 된다.
x
public class NumberFun {    public static long findNextSquare(long sq) {        if (Math.round(Math.sqrt(sq)) == Math.sqrt(sq))            return (long) Math.pow(Math.sqrt(sq) + 1, 2);        return -1;
    }}
루트 값을 반올림하여 루트값과 일치하면 그 다음 큰 값의 제곱 값을 리턴하고, 일치하지 않으면 -1을 리턴하게 했다.
3항 연산자를 사용하면 한줄로 줄일 수 있었겠지만, 가독성이 안좋아질 것 같았다.
무작정 한줄로 줄인다고 해서 무작정 잘 짠 코드라고는 생각하지 않아서 그냥 if문으로 분기하였다.
'공부 > algorithm' 카테고리의 다른 글
| [codewars] Which are in? (0) | 2019.03.29 | 
|---|---|
| [codewars] Who likes it? (0) | 2019.03.24 | 
| [codewars] Dubstep (0) | 2019.03.23 | 
| [algorithm] 방 번호 (0) | 2019.02.22 | 
| [programmers] K번째수 (0) | 2019.01.05 | 
댓글