Notice
Recent Posts
Recent Comments
Link
«   2025/07   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

개발 일지

728. Self Dividing Numbers (자기 분할 숫자) 본문

코딩 테스트/LeetCode

728. Self Dividing Numbers (자기 분할 숫자)

포카리tea 2023. 5. 15. 01:22

자가 분할 숫자는 포함된 모든 숫자로 구분할 수 있는 숫자입니다.

예를 들어 128은 128% 1 == 0, 128% 2 == 0 및 128% 8 == 0이기 때문에 자체 분할 숫자입니다.
숫자 0을 포함하는 숫자는 허용되지 않습니다.

왼쪽과 오른쪽에 두 개의 정수가 주어지면 [왼쪽, 오른쪽] 범위에 있는 모든 자 분할 숫자 목록을 반환합니다.

예시 1:

입력: left = 1, right = 22
출력: [1,2,3,4,5,6,7,8,9,11,12,15,22]

 

예시 2:

입력: left = 47, right = 85
출력: [48,55,66,77]

 

조건:

  • 1 <= left <= right <= 10^4

 

정답:

public class Solution {
    public IList<int> SelfDividingNumbers(int left, int right) 
    {
       List<int> result = new List<int>();

        for (int i = left; i <= right; i++)
        {
            bool check = true;
            string istring = i.ToString();
            
            for (int j = 0; j < istring.Length; j++)
            {
                if (int.Parse(istring[j].ToString()) == 0)
                {
                    check = false;
                }
                else
                {
                    if (i % int.Parse(istring[j].ToString()) != 0)
                    {
                        check = false;
                    }
                }
            }

            if (check)
            {
                result.Add(i);
            }
        }

        return result;
    }
}

해설: 

숫자 i를 문자열로 변형하여 해당 문자열의 j번째 숫자로 나누어서 자기 분할 숫자인지 확인하여 result에 넣어주고 반환해주었습니다.