LeetCode[202] Happy Number
1. 題目
Write an algorithm to determine if a number 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, and 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 numbers.
Example:
1 | Input: 19 |
Explanation:
- 1 * 1 + 9 * 9 = 82
- 8 * 8 + 2 * 2 = 68
- 6 * 6 + 8 * 8 = 100
- 1 * 1 + 0 * 0 + 0 * 0 = 1
2. 思路
因為不是Happy number的話會進入迴圈 (loops endlessly in a cycle) 所以可想到 floyd’s cycle detection
3.解題
1 | int check_happy(int target) |
本部落格所有文章除特別聲明外,均採用 CC BY-NC-SA 4.0 許可協議。轉載請註明來自 LuYee6813's Blog!