LeetCode 168. Excel Sheet Column Title
考点 | 难度 |
---|---|
String | Easy |
题目
Given an integer n, return a string array answer (1-indexed) where:
answer[i] == "FizzBuzz"
if i
is divisible by 3 and 5.
answer[i] == "Fizz"
if i
is divisible by 3.
answer[i] == "Buzz"
if i
is divisible by 5.
answer[i] == i
(as a string) if none of the above conditions are true.
思路
对于每一位判断是否被3或5整除。重点是Integer.toString(num)
。
答案
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;
}