0%

codewar-判斷數字是否為平方

題目:判斷數字是否為平方

1
2
3
4
5
6
7
8
9
10
describe "is_square" do
it "should work for some examples" do
Test.assert_equals (is_square (-1)), false, "-1 is not a perfect square"
Test.assert_equals (is_square 0), true, "0 is a perfect square (0 * 0)"
Test.assert_equals (is_square 3), false, "3 is not a perfect square"
Test.assert_equals (is_square 4), true, "4 is a perfect square (2 * 2)"
Test.assert_equals (is_square 25), true, "25 is a perfect square (5 * 5)"
Test.assert_equals (is_square 26), false, "26 is not a perfect square"
end
end

解題方向:

先排除掉負值,如果是平方,開根號會是整數,所以除以1會等於0,反之則否。所以直接將參數開根號去除以1去餘數0.

1
2
3
4
def is_square(x)
#x等於0,或開根號後得到整數
x >= 0 && Math.sqrt(x) % 1 == 0
end