[leetcode][C] 202번 - Happy Number

numango·2024년 9월 4일

leetcode

목록 보기
1/12

문제

Write an algorithm to determine if a number n is happy.
A happy number is a number defined by the following process:
Starting with any positive integer, replace the number by the sum of the squares of its digits.
Repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1.
Those numbers for which this process ends in 1 are happy.
Return true if n is a happy number, and false if not.

Example 1:

Input: n = 19
Output: true
Explanation:
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1

Constraints:

1 <= n <= 231 - 1


숫자 n이 주어지고 각 자리 숫자의 제곱의 합 1이면 true를, 무한루프에 빠지면 false을 반환하라고 한다.

무한루프를 반복하게 하는 숫자가 있을 거 같아서 식을 전개해 봤더니 공통으로 sum 값이 89가 되면 무한루프에 빠진다는 것을 발견했다.

따라서 sum이 89일 때 false를 반환하도록 작성했다.

bool isHappy(int n) {
    int sum = 0;  //n의 각 자리 숫자의 제곱의 합
    
    while(n>0){
        int num = n%10;
        sum += num*num;
        n = n/10;
    }
    n = sum;  //while문에서 n값이 바뀌었으므로 다시 대입
    
    if(sum == 1){return 1;} 
    else{
        while(n>0){
            sum = 0; //sum값 초기화
            while(n>0){
                int num = n%10;
                sum += num*num;
                n = n/10;
            }
            n = sum; //n값 초기화
            if(n == 1){return 1;}
            else if(n==89){return 0;} //무한루프에 빠지면 false 반환        
        }
    }
    return 0;
}

0개의 댓글