[抄题]:
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: 19 is a happy number
- 12 + 92 = 82
- 82 + 22 = 68
- 62 + 82 = 100
- 12 + 02 + 02 = 1
[暴力解法]:
时间分析:
空间分析:
[优化后]:
时间分析:
空间分析:
[奇葩输出条件]:
[奇葩corner case]:
[思维问题]:
[一句话思路]:
对n进行 / 10等处理操作,循环条件是 n > 0
[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):
[画图]:
[一刷]:
[二刷]:
[三刷]:
[四刷]:
[五刷]:
[五分钟肉眼debug的结果]:
[总结]:
while (n > 0)的条件下,需要反复操作
[复杂度]:Time complexity: O(n) Space complexity: O(n)
[英文数据结构或算法,为什么不用别的数据结构或算法]:
hashset重复性:加不进
[关键模板化代码]:
while (n > 0) { remain = n % 10; squareSum += remain * remain; n = n / 10; }
[其他解法]:
[Follow Up]:
[LC给出的题目变变变]:
[代码风格] :
class Solution { public boolean isHappy(int n) { //cc if (n == 0) { return false; } //ini int squareSum, remain; Set set = new HashSet(); //while loop, contains while (set.add(n)) { squareSum = 0; while (n > 0) { remain = n % 10; squareSum += remain * remain; n = n / 10; } if (squareSum == 1) return true; n = squareSum; } return false; } }