2 Star 10 Fork 2

CG国斌 / myleetcode

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
_412.java 2.13 KB
一键复制 编辑 原始数据 按行查看 历史
CG国斌 提交于 2020-10-18 09:51 . 维护简单问题结婚
package com.hit.basmath.interview.top_interview_questions.easy_collection.math;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* 412. Fizz Buzz
* <p>
* 写一个程序,输出从 1 到 n 数字的字符串表示。
* <p>
* 1. 如果 n 是3的倍数,输出“Fizz”;
* 2. 如果 n 是5的倍数,输出“Buzz”;
* 3.如果 n 同时是3和5的倍数,输出 “FizzBuzz”。
* <p>
* 示例:
* <p>
* n = 15,
* <p>
* 返回:
* [
* "1",
* "2",
* "Fizz",
* "4",
* "Buzz",
* "Fizz",
* "7",
* "8",
* "Fizz",
* "Buzz",
* "11",
* "Fizz",
* "13",
* "14",
* "FizzBuzz"
* ]
*/
public class _412 {
public List<String> fizzBuzz(int n) {
List<String> ans = new ArrayList<String>();
for (int num = 1; num <= n; num++) {
boolean divisibleBy3 = (num % 3 == 0);
boolean divisibleBy5 = (num % 5 == 0);
if (divisibleBy3 && divisibleBy5) {
ans.add("FizzBuzz");
} else if (divisibleBy3) {
ans.add("Fizz");
} else if (divisibleBy5) {
ans.add("Buzz");
} else {
ans.add(Integer.toString(num));
}
}
return ans;
}
public List<String> fizzBuzz2(int n) {
List<String> ans = new ArrayList<String>();
HashMap<Integer, String> fizzBizzDict =
new HashMap<Integer, String>() {
private static final long serialVersionUID = 7966206953841139705L;
{
put(3, "Fizz");
put(5, "Buzz");
}
};
for (int num = 1; num <= n; num++) {
StringBuilder numAnsStr = new StringBuilder();
for (Integer key : fizzBizzDict.keySet()) {
if (num % key == 0) {
numAnsStr.append(fizzBizzDict.get(key));
}
}
if (numAnsStr.toString().equals("")) {
numAnsStr.append(Integer.toString(num));
}
ans.add(numAnsStr.toString());
}
return ans;
}
}
Java
1
https://gitee.com/guobinhit/myleetcode.git
git@gitee.com:guobinhit/myleetcode.git
guobinhit
myleetcode
myleetcode
master

搜索帮助