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" ]
这一题确实太简单,没什么好说的,介绍两种方法:
方法一:逐个判断是不是3的倍数,5的倍数,15的倍数。需要说明的是,判断条件的先后顺序:可以把出现次是比较多的判断条件尽量放前面,这样可以减少判断次数。
public class Solution {
private static final String FIZZ = "Fizz";
private static final String BUZZ = "Buzz";
private static final String FIZZBUZZ = "FizzBuzz";
public List<String> fizzBuzz(int n) {
List<String> list = new ArrayList<>();
int nCurrent = 0;
while (nCurrent < n) {
nCurrent++;
if (nCurrent % 3 != 0 && nCurrent % 5 != 0) {
list.add(String.valueOf(nCurrent));
continue;
}
if (nCurrent % 15 == 0) {
list.add(FIZZBUZZ);
continue;
}
if (nCurrent % 3 == 0) {
list.add(FIZZ);
continue;
}
if (nCurrent % 5 == 0) {
list.add(BUZZ);
continue;
}
}
return list;
}
}
上面的continue,还可以用else if
方法二:先把所有的String用数字填满,然后依次修改3的倍数,5的倍数,15的倍数。
总结:理论上,两个方法复杂度的数量级一样,都是O(n),但是方法二在系数上要大于方法一,因此要慢一点。做了改进以后,方法二的速度有了少许的提高。
public class Solution {
private static final String FIZZ = "Fizz";
private static final String BUZZ = "Buzz";
private static final String FIZZBUZZ = "FizzBuzz";
public List<String> fizzBuzz(int n) {
List<String> list = new ArrayList<>();
int nCurrent = 0;
while (nCurrent < n) {
nCurrent++;
list.add(String.valueOf(nCurrent));
}
int nRadio = 1;
while (nRadio * 3 <= n) {
list.set(nRadio * 3 - 1, FIZZ);
nRadio++;
}
nRadio = 1;
while (nRadio * 5 <= n) {
list.set(nRadio * 5 - 1, BUZZ);
nRadio++;
}
nRadio = 1;
while (nRadio * 15 <= n) {
list.set(nRadio * 15 - 1, FIZZBUZZ);
nRadio++;
}
return list;
}
}
下面是以上代码的速度上的改进,不是直接用的list,而是使用的String数组,最后转成list:
public class Solution {
private static final String FIZZ = "Fizz";
private static final String BUZZ = "Buzz";
private static final String FIZZBUZZ = "FizzBuzz";
public List<String> fizzBuzz(int n) {
String[] strArr = new String[n];
List<String> list = new ArrayList<>();
for (int i = 0; i < strArr.length; i++) {
strArr[i] = String.valueOf(i+1);
}
int nRadio = 1;
while (nRadio * 3 <= n) {
strArr[nRadio * 3 - 1] = FIZZ;
nRadio++;
}
nRadio = 1;
while (nRadio * 5 <= n) {
strArr[nRadio * 5 - 1] = BUZZ;
nRadio++;
}
nRadio = 1;
while (nRadio * 15 <= n) {
strArr[nRadio * 15 - 1] = FIZZBUZZ;
nRadio++;
}
return Arrays.asList(strArr);
}
}
总结:理论上,两个方法复杂度的数量级一样,都是O(n),但是方法二在系数上要大于方法一,因此要慢一点。做了改进以后,方法二的速度有了少许的提高。