【哈希】【快慢指针】202. 快乐数
题目:
编写一个算法来判断一个数 n 是不是快乐数。
「快乐数」定义为:对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和,然后重复这个过程直到这个数变为 1,也可能是 无限循环 但始终变不到 1。如果 可以变为 1,那么这个数就是快乐数。
如果 n 是快乐数就返回 True ;不是,则返回 False 。
示例:
输入:19
输出:true
解释:
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
题目主要要解决如何判断是否无限循环问题
方法一:快慢指针
题目中含有一个隐式链表,判断循环使用快慢指针
class Solution { //存在隐式链表 public int getNext(int n) { int totalSum = 0; while (n > 0) { int d = n % 10; n = n / 10; totalSum += d * d; } return totalSum; } //快慢指针判断循环 public boolean isHappy(int n) { int slowRunner = n; int fastRunner = getNext(n); while (fastRunner != 1 && slowRunner != fastRunner) { slowRunner = getNext(slowRunner); fastRunner = getNext(getNext(fastRunner)); } return fastRunner == 1; } }
方法二:用HashSet判断是否无限循环
class Solution { public boolean isHappy(int n) { HashSet<Integer> set = new HashSet<>(); while(true){ int num = cal(n); if(num == 1){ return true; } if(set.contains(num)){ return false; } set.add(num); n = num; } } public int cal(int n){ int res = 0; while(n>0){ res +=(n%10)*(n%10); n = n/10; } return res; } }

浙公网安备 33010602011771号