A simple ruby solution


  • 0
    Y

    I'm a fresh ruby learner, so I try to use it.....

    @param {Integer} n

    @return {Boolean}

    def is_happy(n)
    bigHash = {}
    key = 0
    value = 0
    temp_num = n
    flag = true
    ret = true

    while flag do
        key = temp_num.to_s.split("").sort.join
        # has-key before, endless, so break
        if !bigHash[key].nil?
            ret = false
            break
        end 
        bigHash[key] = 1 
        new_num = 0 
        temp_num.to_s.split("").map{|k| new_num+=k.to_i ** 2}
    
        # ==1, then it's happy number
        if new_num == 1
            ret = true
            break
        end 
        temp_num = new_num
    end 
    ret 
    

    end


  • 0
    R
    def is_happy(n)
      cache = {}
      while (n != 1)
        int_ary = n.to_s.split('').map &:to_i
        square_ary = int_ary.map { |i| i**2 }
        n = square_ary.reduce &:+
        return false if cache[n]
        cache[n] = 1
      end
      return true
    end
    

  • 0
    Y

    much thanks to your short answer, it's really awesome


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.