題目要求
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
剛看到這道題目的時候以為以為很簡單,很快寫完,但一直不通過,后來仔細檢查,發(fā)現(xiàn)要注意的地方還挺多。
一、剛開始只寫了循環(huán)部分,并沒有建立數(shù)組,導致打印出來只有結果,并不是一個數(shù)組,導致出錯;
二、數(shù)組中添加元素的方法:
1、newArr.push("Fizz")
2、newArr<<"Fizz"
3、newAr.insert(2,"Fizz")
- Ruby 字符串分為單引號字符串(')和雙引號字符串("),區(qū)別在于雙引號字符串能夠支持更多的轉(zhuǎn)義字符。在Ruby中,可以通過在變量或者常量前面加 # 字符,來訪問任何變量或者常量的值。
三、

范圍運算符