I was doing a simple fizzbuzz
problem in Java and encountered a bug that I cannot find for the life of me. The "fizz" is not added to the result unless the number is also divisible by 5.
actual: ["1","2","3","4","buzz","6","7","8","9","buzz","11","12","13","14","fizzbuzz"]
expected: ["1","2","fizz","4","buzz","fizz","7","8","fizz","buzz","11","fizz","13","14","fizzbuzz"]
public List<String> fizzBuzz(int n) {
List<String> result = new ArrayList<>();
for (int i = 1; i <= n; i ) {
String word = "";
if (i % 3 == 0) {
word = "fizz";
} if (i % 5 == 0) {
word = "buzz";
} else {
word = String.valueOf(i);
}
result.add(word);
}
return result;
}
CodePudding user response:
You have two if
block instead of one.
if (i % 3 == 0) {
word = "fizz";
} if (i % 5 == 0) {
word = "buzz";
} else {
word = String.valueOf(i);
}
In the above block first condition is if the i
is divisible by 3 and immediately it will check if the i
is divisible by 5 else it will execute the else part.
In case of i
being divisible 3
and not divisible by 5
you will always get the i
value.
for your requirement you could do as follows
if (i % 3 == 0 && i % 5 == 0) {
word = "fizzbuzz";
} else if (i % 3 == 0) {
word = "fizz";
} else if (i % 5 == 0) {
word = "buzz";
} else {
word = String.valueOf(i);
}
This way first you are check if the value is both divisible by 3 and 5 if not then divisible by 3 if not then divisible by 5 and finally else part.
CodePudding user response:
public static List<String> fizzBuzz(int n) {
List<String> res = new ArrayList<>(n);
for (int i = 1; i <= n; i ) {
boolean mulThree = i % 3 == 0;
boolean mulFive = i % 5 == 0;
if (mulThree && mulFive)
res.add("FizzBuzz");
else if (mulThree)
res.add("Fizz");
else if (mulFive)
res.add("Buzz");
else
res.add(String.valueOf(i));
}
return res;
}