class Solution {
public long solution(long n) {

long answer = -1;

double sqrt = Math.sqrt(n);
double rnd = Math.round(sqrt * 100000000) / 100000000.0;

String str = String.valueOf(rnd);
int idx = str.indexOf(".");
int count = 0;

for (int i = idx + 1; i < str.length(); i++) {
if (str.charAt(i) != '0')
count++;
}

if (count == 0) {

answer = Long.valueOf(str.substring(0, idx)) + 1;
double pow = Math.pow(answer, 2);
String last = String.valueOf((int) pow);
answer = Long.valueOf(last);
}
return answer;
}
}


좀 복잡하게 푼거 같다. 정수를 문자열로 바꾸어 소수점이 0이 아니면 제곱근이 아니므로 -1을 리턴하게 했다.  다른 사람의 풀이를 보니 이렇게 할 필요가 없었다....


class Solution {
public long solution(long n) {

long sqrt = (long) Math.sqrt(n);
System.out.println(sqrt);

if (Math.pow(sqrt, 2) == n)
return (long) Math.pow((sqrt + 1), 2);


return -1;
}

}

어차피 long으로 형변환을 하면 정수로 나오기 때문에 이를 다시 제곱해서 n값과 비교하면 된다.


배운점 

타입의 중요성, sqrt, pow 메소드



공부할 것

숫자 타입


BELATED ARTICLES

more