导航
导航
文章目录
  1. 题目
  2. 翻译

LeetCode-412.Fizz Buzz

题目

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”
]

翻译

编写程序,输出从1到n的字符串
但当遇到3的倍数时,输出”Fizz”;当遇到5的倍数时,输出”Buzz”。当遇到既是3又是5的倍数的数字时,输出”FizzBuzz”。

一共四种情况:
A.既能被3又能被5整除,放入FizzBuzz;
B.只能被3整除,放入Fizz;
C.只能被5整除,放入Buzz;
D.既不能被3整除又不能被5整除,放入当前数字。
按照顺序判断即可,但判断A情况时不用先判断3再判断5,直接判断是否可被15整除即可:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class Solution {
public List<String> fizzBuzz(int n) {
List<String> res = new ArrayList<String>();
for (int i = 1; i <= n; i++) {
String cur = "";
if (i % 15 == 0) cur = "FizzBuzz";
else if (i % 3 == 0) cur = "Fizz";
else if (i % 5 == 0) cur = "Buzz";
else cur += i;
res.add(cur);
}

return res;
}
}