본문 바로가기
IT/알고리즘

23] Leetcode 728. Self Dividing Numbers

by 깻잎쌈 2020. 7. 4.
반응형

https://leetcode.com/problems/self-dividing-numbers/

 

Self Dividing Numbers - 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

범위 내 숫자들 중에 각 자릿수로 나눠 떨어지는 숫자의 개수를 반환하는 문제.

 

안 되는 숫자는 0을 포함하고 있거나, 나눠 떨어지지 않는 경우이다.

그 경우만 제외하고 vector에 넣어주면 된다.

class Solution {
public:
    vector<int> selfDividingNumbers(int left, int right) {
        vector<int>ans;
        int num=0;
        bool yes = false;
        
        for(int i = left; i<=right; i++){
            num=i;
            yes = true;
            while(num){
                // 0이 나오면 break
                if(num %10 == 0){
                    yes=false;
                    break;
                }   
                // 안 나눠떨어져도 break
                if(i % (num %10) != 0){
                    yes = false;
                    break;
                }
                else{
                    num /=10;
                 
                }
            }
            
            if(yes)
                ans.push_back(i);
        }
        
        return ans;
    }
};
반응형

댓글