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”.
1부터 n까지의 숫자를 문자열 표현으로 출력하는 프로그램을 작성하라.
3의 배수에 대해서는 "Fizz", 5의 배수에 대해서는 "Buzz",
3의 배수이고 또한 5의 배수인 경우 "FizzBuzz"를 출력하라.
풀이 방법
1. return 형식에 맞는 ArrayList를 만든다.
2. 각 배수에 따른 문자열을 list에 추가한다.
3. list를 return한다.
알린이인 내게도 너무나도 간단했던 문제...
class Solution {
public List<String> fizzBuzz(int n) {
List<String> list = new ArrayList<String>();
for(int i=1; i<=n; i++) {
if(i%3 == 0 && i%5 == 0) {
list.add("FizzBuzz");
} else if(i%3 == 0) {
list.add("Fizz");
} else if(i%5 == 0) {
list.add("Buzz");
} else {
list.add(Integer.toString(i));
}
}
return list;
}
}
'알고리즘 > LeetCode' 카테고리의 다른 글
[JAVA] LeetCode 108 - Convert Sorted Array to Binary Search Tree (0) | 2020.11.16 |
---|---|
[JAVA] LeetCode 206 - Reverse Linked List (0) | 2020.11.16 |
[JAVA] LeetCode 237 - Delete Node in a Linked List (0) | 2020.11.14 |
[JAVA] LeetCode 136 - Single Number (0) | 2020.11.14 |
[JAVA] LeetCode 104 - Maximum Depth of Binary Tree (0) | 2020.11.14 |