2017-09-20 146 views
0

我是學習Ruby語言的初學者。 我正在研究它從leetcode。Ruby中的醜陋數字

這裏有一個解決方案,但我不知道爲什麼? 我想知道什麼是結構在溶液

醜數 解決方案:

def is_ugly(num) 
    (2..5).each { |i| num /= i while (num % i == 0) } if num > 0 
    num == 1 
end 
  1. 我不知道爲什麼「如果」有背後「}」

    如果我刪除'if'語句將會出錯

    語法錯誤,意外的輸入結束,expectin摹keyword_end

  • while (num % i == 0) 我無法理解這樣的說法

    據我所知,而似乎是:

  • 例如。

    while conditional [do] 
        code 
    end 
    

    非常感謝

    +0

    *「這裏有一個解決辦法,但我不知道爲什麼?」 * ---我真的不能解釋爲什麼這種「解決方案」的作品,不知道問題!什麼是定義爲「醜陋」的數字? –

    +0

    是[this](https://leetcode.com/problems/ugly-number/description/)的問題? 「醜陋的數字是正數,其主要因素只包括2,3,5」。 –

    回答

    4

    兩個ifwhile被所謂的後綴(短)的形式。

    嘗試這些:

    puts "yes" if true 
    

    puts "yes" if false 
    

    它基本上是一樣的:

    if true 
        puts "yes" 
    end 
    

    while

    num /= i while (num % i == 0) 
    

    是完全一樣的

    while (num % i == 0) 
        num = num/i 
    end