๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm ๐Ÿง‘๐Ÿป‍๐Ÿ’ป/Leetcode

[Leetcode,c++] Happy Number

by dkswnkk 2022. 3. 2.

๋ฌธ์ œ

 

Happy Number - 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

 

์ฝ”๋“œ

class Solution {
public:
    bool isHappy(int n) {
        string s;
        s = to_string(n);
        while(true){
            unsigned long long temp = 0;
            for(int i=0; i<s.length(); i++){
                temp += pow(s[i]-'0',2);
            }
            if(temp==1||temp==7) return true;
            if(temp<10&&temp!=1) return false;
            s = to_string(temp);
        }
    }
};

ํ’€์ด

Happy Number, ์ฆ‰ ํ–‰๋ณตํ•œ ์ˆ˜ ์ธ์ง€ ์•„๋‹Œ์ง€ ํŒ๋ณ„ํ•˜๋Š” ๋ฌธ์ œ์ž…๋‹ˆ๋‹ค. ํ–‰๋ณตํ•œ ์ˆ˜๋ž€ ์ž์—ฐ์ˆ˜๊ฐ€ ์ฃผ์–ด์กŒ์„ ๋•Œ ์ž์—ฐ์ˆ˜์˜ ๊ฐ ์ž๋ฆฟ์ˆ˜์˜ ์ œ๊ณฑ์˜ ํ•ฉ์ด ๊ฒฐ๊ตญ 1์ด ๋˜๋Š” ๊ฒฝ์šฐ๋ฅผ ํ–‰๋ณตํ•œ ์ˆ˜๋ผ๊ณ  ์นญํ•ฉ๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค๋ฉด ์•„๋ž˜์™€ ๊ฐ™์Šต๋‹ˆ๋‹ค.

n = 19
1^2 + 9^2 = 82
8^2 + 2^2 = 68
6^2 + 8^2 = 100
1^2 + 0^2 + 0^2 = 1

๊ฒฐ๊ตญ 1์ด ๋˜์–ด 19๋Š” ํ–‰๋ณตํ•œ ์ˆ˜๊ฐ€ ๋ฉ๋‹ˆ๋‹ค.

n = 7
7^2 = 49
4^2 + 9^2 = 97
9^2 + 7^2 = 130
1^2 + 3^2 + 0^2 = 10
1^2 + 0^2 = 1

๊ฒฐ๊ตญ 1์ด ๋˜์–ด 7์€ ํ–‰๋ณตํ•œ ์ˆ˜๊ฐ€ ๋ฉ๋‹ˆ๋‹ค.

ํ–‰๋ณตํ•œ ์ˆ˜์— ๋Œ€ํ•œ ์ € ์ž์„ธํ•œ ์„ค๋ช…์€ ์•„๋ž˜ ๋ธ”๋กœ๊ทธ์— ์ž˜ ๋‚˜์™€ ์žˆ์œผ๋‹ˆ ํ•œ๋ฒˆ ๋ณด์‹œ๋ฉด ๋  ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.

 

ํ–‰๋ณตํ•œ ์ˆ˜: Happy number

์ €๋ฒˆ ์ผ์š”์ผ์— ์ƒˆ๋กœ ์•Œ๊ฒŒ ๋œ ์ˆ˜์˜ ์ข…๋ฅ˜์ธ๋ฐ ์ €๋Š” ์ด ์ˆ˜๋ฅผ ์•Œ๊ฒŒ ๋œ ๊ณผ์ •์ด ๊ทธ ์ˆ˜์˜ ์ด๋ฆ„๊ณผ ๋ฐ˜๋Œ€์˜€์Šต๋‹ˆ๋‹ค... ๋ฐ”๋กœ happy number, ๋ฒˆ์—ญํ•˜๋ฉด 'ํ–‰๋ณตํ•œ ์ˆ˜'๋ผ๊ณ  ํ•˜๋Š”๋ฐ์š”, ์ €๋Š” ํ”„๋กœ๊ทธ๋ž˜๋ฐ ์‹œํ—˜์„ ๋ณด๋‹ค๊ฐ€ ์•Œ

miretia.tistory.com

Input์œผ๋กœ ๋“ค์–ด์˜ค๋Š” ์ตœ๋Œ€ ์ˆ˜๊ฐ€ 2^31- 1 ์œผ๋กœ์จ 21์ž๋ฆฌ ๋ฐ–์— ๋˜์ง€ ์•Š๊ธฐ ๋•Œ๋ฌธ์— for๋ฌธ์œผ๋กœ ๊ฐ ์ž๋ฆฟ์ˆ˜๋ฅผ ์ œ๊ณฑํ•ด๊ฐ€๋ฉด์„œ ๋งŒ์•ฝ ์ž์—ฐ์ˆ˜๊ฐ€ ํ•œ์ž๋ฆฌ ์ˆ˜ ์ผ ๋•Œ 1 ํ˜น์€ 7์ด๋ฉด true๋ฅผ return ํ•ด์ฃผ๋Š” ์‹์œผ๋กœ ํ’€์ดํ–ˆ์Šต๋‹ˆ๋‹ค.

'Algorithm ๐Ÿง‘๐Ÿปโ€๐Ÿ’ป > Leetcode' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

[Leetcode,c++] Add Digits  (0) 2022.03.02
[Leetcode,c++] Majority Element  (0) 2021.11.28
[Leetcode,c++] Network Delay Time  (0) 2021.11.22
[Leetcode,c++] Valid Anagram  (0) 2021.11.20
[Leetcode,c++] Single Number  (0) 2021.11.19
[Leetcode,c++] Combination Sum II  (0) 2021.11.16

๋Œ“๊ธ€