知之者 不如好之者, 好之者 不如樂之者

기계처럼 살지 말고, 즐기는 인간이 되자

Code/LeetCode

[LeetCode] 202. Happy Number (Easy/Python)

코방코 2023. 3. 5. 11:31
728x90
 

Happy Number - LeetCode

Can you solve this real interview question? Happy Number - 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 squar

leetcode.com

Above is the link to the problem.

 

Problem

A happy number is a number defined by the following process

1. Starting with any positive integer, replace the number with the sum of the squares of its digits.

2. Repeat the process until the number equals 1 → Happy number : Return True,

or it loops endlessly in a cycle that does not include 1 → Unhappy number : Return False.

 

Example 1

Input: n = 19

Output: true

Explanation:

1^2 + 9^2 = 82

8^2 + 2^2 = 68

6^2 + 8^2 = 100

1^2 + 0^2 +0^2 = 1

 

Example 2

Input: n = 2

Output: false

Explanation:

2^2  = 4

4^2 = 16

1^2 + 6^2 = 37

3^2 + 7^2 = 58

5^2 + 8^2 = 89

8^2 + 9^2 = 145

1^2 + 4^2 +5^2 = 42

4^2 + 2^2 = 20

2^2 + 0^2 = 4

→ endless loop

 

Code

 

This code gets the top 37.81% of time complexity and uses 13.7MB of memory.

 

728x90
반응형