题目1 题解1 class Solution: def hammingWeight(self, n: int) -> int: sum = 0 # 每次减去一个1,然后与原值相与,得到的值会少一个1 while n != 0: sum += 1 n &= (n-1) return sum 附上题目链接 题目2 题解2 def isHappy(self, n: int) -> bool: def get_next(n): total_sum = 0 while n > 0: n, digit = divmod(n, 10) total_sum += digit ** 2 return total_sum # 常见一个集合,用来证明是否进入死循环 seen = set() while n != 1 and n not in seen: seen.add(n) n = get_next(n) return n == 1 附上题目链接 题目3 题解3 # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def removeElements(self, head: ListNode, val: int) -> ListNode: """ 遍历链表 """ # 常见一个虚假节点 fakeNode = ListNode("inf") fakeNode.next = head p = fakeNode n = fakeNode.next while n: if n.val == val: p.next = p.next.next else: p = p.next n = n.next return fakeNode.next def removeElements(self, head: ListNode, val: int) -> ListNode: """ 递归法 """ if head is None: return head.next = self.removeElements(head.next, val) return head.next if head.val == val else head 附上题目来链接