https://leetcode.com/problems/happy-number/description
Q. 해당 정수 number가 주어질 때, 이것이 happy number 인지 판단하라.
각 자리수를 반복해서 더한 합이 1 이 되면 이것을 happy number라고 부른다.

Solution.
우선 happy number가 되는지 판별하는 코드를 만든다.
happy number가 되지 않으면 해당 과정을 다시 밟는데,
특정 숫자들은 기존에 나왔던 숫자셋이 다시 나오기 시작한다.
이렇게 되면 이 과정이 무한히 반복되게 된다.
이때 이 숫자는 happy number가 되지 않는다고 판단할 수 있다.
다만 숫자 자리수 조합을 비교할 때, 같은 조합인지를 비교해야하므로, 여러가지 방법으로 이를
체크 할 수 있다.
여기서는 정렬로 숫자를 확인한다.
로직 구현 과정에 큰 문제는 없어 보인다.
더보기
string SortString(string strIn)
{
char[] chStr = strIn.ToArray();
Array.Sort(chStr);
return new string(chStr);
}
public bool IsHappy(int number)
{
HashSet<string> hashNums = new HashSet<string>();
hashNums.Add($"{number}");
int n = number;
while(true)
{
List<int> digits = new List<int>();
while(n>0)
{
int val = n%10;
digits.Add(val);
n /= 10;
}
int sum = 0;
for(int q = 0; q < digits.Count; ++q)
sum += (digits[q] * digits[q]);
if(sum == 1) return true;
string strSorted = SortString( $"{sum}" );
if(hashNums.Contains(strSorted))
return false;
hashNums.Add(strSorted);
n = sum;
}
return false;
}
적절한 결과.

'Leetcode > Top Interview 150' 카테고리의 다른 글
| [Intervals][Easy] 228. Summary Ranges (0) | 2024.05.08 |
|---|---|
| [Hashmap][Easy] 219. Contains Duplicate II (0) | 2024.05.07 |
| [Hashmap][Medium] 49. Group Anagrams (0) | 2024.05.07 |
| [Hashmap][Easy] 242. Valid Anagram (0) | 2024.05.06 |
| [Hashmap][Easy] 290. Word Pattern (0) | 2024.05.06 |