你必須很努力

換刷 Codewars - Find the next perfect square!

2019/09/12
字數統計: 302閱讀時間: 1 min

昨天被 LeetCode 摧殘幼小心靈
才不會說是 LeetCode 題目卡關呢
今天換個輕鬆小品來撫慰下自己
Codewars 的題目友善許多
學過 Ruby 對於常見方法知道如何應用時
能很快地解出 Level 8 的題目
過程卡關時,可透過關鍵字查詢
說不定會發現不知道的方法


Ruby 有許多更簡單的方法
這是老師常告訴我們的話
會說我們寫太複雜了 XD
(小離題 趕緊拉回


從 Level 8 開始挑戰吧
題目

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
def find_next_square(sq)

end


describe "find_next_square" do
it "should return the next square for perfect squares" do
Test.assert_equals(find_next_square(121), 144, "Wrong output for 121")
Test.assert_equals(find_next_square(625), 676, "Wrong output for 625")
Test.assert_equals(find_next_square(319225), 320356, "Wrong output for 319225")
Test.assert_equals(find_next_square(15241383936), 15241630849, "Wrong output for 15241383936")
end

it "should return -1 for numbers which aren't perfect squares" do
Test.assert_equals(find_next_square(155), -1, "Wrong output for 155")
Test.assert_equals(find_next_square(342786627), -1, "Wrong output for 342786627")
end
end

解題過程其實很快
花比較多時間講解說明
也可直接看下方解題答案
有更好方法歡迎留言互相交流!


答案:

1
2
3
def find_next_square(sq)
sq.pow(0.5) % 1 == 0 ? (Math.sqrt(sq).to_i + 1).pow(2) : -1
end

本文同步發布於 小菜的 Blog https://riverye.com/

原文連結:https://riverye.com/2019/09/12/換刷-Codewars-Find-the-next-perfect-square/

發表日期:2019-09-12

更新日期:2022-12-21

CATALOG