本题涉及判断是否有loop
两种思路:1.用set存储路径 2.快慢指针法
JAVA:set()集合法
class Solution { public boolean isHappy(int n) { Set<Integer> process = new HashSet<>(); while(process.add(n)){ int square = 0; while(n != 0){ square += (n % 10)*(n % 10); n /= 10; } if(square == 1) return true; else n = square; } return false; } }
JAVA:快慢指针法
class Solution { public boolean isHappy(int n) { int slow = n; int fast = square(n); while(fast != 1){ slow = square(slow); fast = square(fast); fast = square(fast); if(slow == fast) return false; } return true; } public int square(int n){ int res = 0; while(n != 0){ res += (n%10)*(n%10); n /= 10; } return res; } }
python3:set()集合法
class Solution: def isHappy(self, n: int) -> bool: process = set() while n != 1: n = sum([int(x)**2 for x in str(n)]) if n in process: return False else: process.add(n) return True
python3:快慢指针法
class Solution: def isHappy(self, n: int) -> bool: slow = n fast = self.square(n) while fast != 1: slow = self.square(slow) fast = self.square(fast) fast = self.square(fast) if slow == fast: return False return True def square(self, n): res = 0 while n: res += (n % 10)**2 n //= 10 return res