【哈希表】leetcode_202_快乐数
c++(找重复,重复了说明不是,set存每一个sum,在set中find)
class Solution {
public:
bool isHappy(int n) {
unordered_set<int> reset;
int sum = 0;
while(sum !=1){
sum = 0;
while(n){
int i = n%10;
sum = sum + i*i;
n=n/10;
}
if (reset.find(sum) !=reset.end()){
return false;
}
reset.insert(sum);
n = sum;
}
return true;
}
};
这里记录两个表:大佬整理的复杂度,所以没有排序要求的话,尽量用unorder_
python(虽然知道这么写不好,但是这个随意的类型转化真的。。。)
class Solution:
def isHappy(self, n: int) -> bool:
re = []
sum = 0
while (n != 1):
re.append(n)
st_n = str(n)
sum = 0
for i in st_n:
i = int(i)
sum = sum + i ** 2
n = sum
if n in re:
return False
return True