Skip to content

Latest commit

 

History

History
52 lines (49 loc) · 947 Bytes

202.md

File metadata and controls

52 lines (49 loc) · 947 Bytes

202. Happy Number

题目链接

思路:如果有一个数字重复出现,那么一定不是Happy Number

class Solution(object):
	def isHappy(self, n):
		"""
		:type n: int
		:rtype: bool
		"""
		num_dict = {}
		while n not in num_dict:
			num_dict[n] = 1
			t = 0
			while n > 0:
				i = n % 10
				t = t + i * i
				n = n / 10
			n = t
			if n == 1:
				return True
		return False

另外一种空间复杂度只需要O(1)的方法,类似于判断循环链表的快慢指针的思想

class Solution(object):
	def isHappy(self, n):
		"""
		:type n: int
		:rtype: bool
		"""
		fast = slow = n
		while True:
			slow = self.getNumber(slow)
			fast = self.getNumber(self.getNumber(fast))
			if slow == fast:
				break
		if slow == 1:
			return True
		return False
		
	def getNumber(self, n):
		t = 0
		while n > 0:
			i = n % 10
			t = t + i * i
			n = n / 10
		return t