코드로 우주평화
Find the next perfect square! 본문
Description:
You 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 then -1 should be returned. You may assume the parameter is non-negative.
Examples:(Input --> Output)
121 --> 144
625 --> 676
114 --> -1 since 114 is not a perfect square
Solution:
1. Find the root value of sq.
2. Check if the root value is divisible by 1.
3. When divisible, add 1 to the root value and find the square root.
4. If not divisible, -1 is returned.
function findNextSquare(sq) {
x = sq**0.5
return x % 1 ? -1 : (x+1)**2
}
The value to find the root is the same as in Python. Use '**'.
In JavaScript, the ternary operator can be used in the following form.
condition ? exprIfTrue : exprIfFalse
Reference:
'나는 이렇게 학습한다 > Algorithm & SQL' 카테고리의 다른 글
Binary Addition (0) | 2022.02.27 |
---|---|
Unique In Order (0) | 2022.02.26 |
Exes and Ohs (0) | 2022.02.24 |
Detect Pangram (0) | 2022.02.23 |
The Hashtag Generator (0) | 2022.02.22 |