LeetCode Top Interview Questions 412. Fizz Buzz (Java版; Easy)
题目描述
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"
]
classSolution{public List<String>fizzBuzz(int n){// ans list
List<String> ans =newArrayList<String>();// Hash map to store all fizzbuzz mappings.
HashMap<Integer, String> fizzBizzDict =newHashMap<Integer, String>(){{put(3,"Fizz");put(5,"Buzz");}};for(int num =1; num <= n; num++){
String numAnsStr ="";
# 遍历哈希表得到映射关系
for(Integer key : fizzBizzDict.keySet()){// If the num is divisible by key,// then add the corresponding string mapping to current numAnsStrif(num % key ==0){
numAnsStr += fizzBizzDict.get(key);}}if(numAnsStr.equals("")){// Not divisible by 3 or 5, add the number
numAnsStr += Integer.toString(num);}// Append the current answer str to the ans list
ans.add(numAnsStr);}return ans;}}
LeetCode Top Interview Questions 412. Fizz Buzz (Java版; Easy)
welcome to my blogLeetCode Top Interview Questions 412. Fizz Buzz (Java版; Easy)题目描述Write a program that outputs the string representation of numbers from 1 to n.But for multiples of three it shou...