Ruby完成FizzBuzz

2017-02-07  本文已影响10人  TW妖妖

题目要求

Write a program that outputs the string representation of numbers from 1 to n.
But for multiples of three it should output “Fizz” instead of the number and for the multiples of five output “Buzz”. For numbers which are multiples of both three and five output “FizzBuzz”.
Example:
n = 15,
Return:
[ "1", "2", "Fizz", "4","Buzz", "Fizz", "7","8","Fizz","Buzz", "11","Fizz", "13", "14", "FizzBuzz"]

代码
# @param {Integer} n
# @return {String[]}
```def fizz_buzz(n)
    newArr = Array.new
    for i in 1..n
        if i%3==0 && i%5==0 
            newArr<< "FizzBuzz"
        elsif i%3==0
            newArr<< "Fizz"
        elsif i%5==0
            newArr<< "Buzz"
        else 
            newArr<< "#{i}"
        end
    end
    newArr
end

刚看到这道题目的时候以为以为很简单,很快写完,但一直不通过,后来仔细检查,发现要注意的地方还挺多。
一、刚开始只写了循环部分,并没有建立数组,导致打印出来只有结果,并不是一个数组,导致出错;
二、数组中添加元素的方法:
1、newArr.push("Fizz")
2、newArr<<"Fizz"
3、newAr.insert(2,"Fizz")

三、


范围运算符
上一篇 下一篇

猜你喜欢

热点阅读