This is the 19th day of my participation in the Gwen Challenge in November. Check out the details: The last Gwen Challenge in 2021.
Title description:
412. Fizz Buzz – LeetCode (leetcode-cn.com)
If you are given an integer n, find the Fizz Buzz of each integer from 1 to n, and return the result with an array of strings (subscript starting from 1) :
answer[i] == "FizzBuzz"
ifi
At the same time is3
和5
Multiples.answer[i] == "Fizz"
ifi
是3
Multiples.answer[i] == "Buzz"
ifi
是5
Multiples.answer[i] == i
If none of the above conditions are met.
The sample a
Input: n = 3 Output: ["1","2","Fizz"]Copy the code
Example 2
Input: n = 5 Output: ["1","2","Fizz","4","Buzz"]Copy the code
Example 3
Input: n = 15 output: [" 1 ", "2", "Fizz", "4", "Buzz", "Fizz", "7", "eight" and "Fizz," "Buzz", "11", "Fizz", "13", 14 ", "FizzBuzz"]Copy the code
Tip:
1 <= n <= 10^4
Thought analysis
simulation
Regardless of the background of the problem, this is really just a simple problem of converting an int array to an array of strings.
With the API, one map will do.
We iterate through 1 to n, converting to Fizz when it’s just a multiple of 3, converting to Buzz when it’s just a multiple of 5, and FizzBuzz when it’s both a multiple of 3 and a multiple of 5. If none of these are satisfied, we return to the original number.
The logic is very simple and clear, just look at the code.
AC code
class Solution {
fun fizzBuzz(n: Int): List<String> {
val answer = ArrayList<String>()
for(i:Int in 1..n) {
var temp:String = ""
if(i%3= =0) {
temp +="Fizz"
}
if(i%5= =0) {
temp +="Buzz"
}
if(temp == "") {
temp += i;
}
answer.add(temp);
}
return answer
}
}
Copy the code
conclusion
The story behind the FizzBuzz than this problem and mean blog.codinghorror.com/why-cant-pr…
FizzBuzz and write code for “10,000” details
Look, it does make sense, everything comes from life, leetcode also.
reference
Fizz Buzz – Fizz Buzz – LeetCode (leetcode-cn.com)
Fizz Buzz – LeetCode (leetcode-cn.com)