LeetCode之Fizz Buzz
生活随笔
收集整理的這篇文章主要介紹了
LeetCode之Fizz Buzz
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1、題目
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" ]2、代碼實現
public class Solution {public List<String> fizzBuzz(int n) {if (n < 0) return null;List<String> list = new ArrayList<String>();for (int i = 1; i <= n; ++i) {if (i % 3 == 0 && i % 5 == 0) {list.add("FizzBuzz");}else if (i % 3 == 0 && i % 5 != 0) {list.add("Fizz");}else if (i % 3 != 0 && i % 5 == 0) {list.add("Buzz");} else {list.add(String.valueOf(i));}}return list;} }?
?
3、總結
我當時寫的時候把 for int = 0; i <= n; ++i 如果輸入i = 0就不行了。
把i = 1開始就對了,因為你看題目輸出,都是從1開始,所以不要慣性思維老是從i ?= 0 開始,i =0 ,i % 3 == 0 ,i % 5 ==0
所以以后寫代碼一定要注意i的初始位置。
總結
以上是生活随笔為你收集整理的LeetCode之Fizz Buzz的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: LeetCode之Keyboard Ro
- 下一篇: LeetCode之Next Greate