题目要求
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")
- Ruby 字符串分为单引号字符串(')和双引号字符串("),区别在于双引号字符串能够支持更多的转义字符。在Ruby中,可以通过在变量或者常量前面加 # 字符,来访问任何变量或者常量的值。
三、