iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 3
0
自我挑戰組

自我挑戰 Ruby 刷題 30 天系列 第 3

換刷 Codewars - Find the next perfect square!

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


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


從 Level 8 開始挑戰吧
題目

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

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


答案:

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/


上一篇
從經典 LeetCode 開始吧 - Two Sum
下一篇
用 TDD 刷 Codewars - Reverse words
系列文
自我挑戰 Ruby 刷題 30 天31
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言