Fizz Buzz
Description:
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 1:
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”。
Solution:
解法一:
死算。
class Solution {
public List<String> fizzBuzz(int n) {
List<String> list = new ArrayList<>();
for (int i = 1; i <= n; i++) {
if (i % 3 == 0 && i % 5 == 0) {
list.add("FizzBuzz");
} else if (i % 3 == 0) {
list.add("Fizz");
} else if (i % 5 == 0) {
list.add("Buzz");
} else {
list.add(String.valueOf(i));
}
}
return list;
}
}
解法二:
没有使用%
符号。多了两个变量记录3的倍数和5的倍数。满足条件清零。
public class Solution {
public List<String> fizzBuzz(int n) {
List<String> ret = new ArrayList<String>(n);
for(int i=1,fizz=0,buzz=0;i<=n ;i++){
fizz++;
buzz++;
if(fizz==3 && buzz==5){
ret.add("FizzBuzz");
fizz=0;
buzz=0;
}else if(fizz==3){
ret.add("Fizz");
fizz=0;
}else if(buzz==5){
ret.add("Buzz");
buzz=0;
}else{
ret.add(String.valueOf(i));
}
}
return ret;
}
}