본문 바로가기
Problem Solving/LeetCode

[LeetCode.412][easy] Fizz Buzz

by Dev Diary Hub 2021. 10. 30.
반응형

https://leetcode.com/problems/fizz-buzz/

 

Fizz Buzz - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

접근 방법

1부터 n까지에 대해 3과5의 공배수인지, 3의 배수인지, 5의 배수인지 체크한다.

O(n)의 시간복잡도를 차지하는 알고리즘으로 풀었다.

 

풀이 코드
class Solution {
public:
    vector<string> fizzBuzz(int n) {
        vector<string> ans;
        
        for(int i=1;i<=n;i++) {
            if(i%3==0 && i%5==0) {
                ans.push_back("FizzBuzz");
                continue;
            }
            
            if(i%3==0) {
                ans.push_back("Fizz");
                continue;
            }
            
            if(i%5==0) {
                ans.push_back("Buzz");
                continue;
            }
            
            ans.push_back(to_string(i));
        }
        
        return ans;
    }
};

 

반응형

'Problem Solving > LeetCode' 카테고리의 다른 글

<Solution> 17.Letter Combinations of a Phone Number  (0) 2022.09.17
[LeetCode.454][middle] 4Sum II  (0) 2021.10.28