zoukankan      html  css  js  c++  java
  • Python(3)

    使用除法来缩减数字,使用余数法来计算个数。

    class Solution:
        def hammingWeight(self, n: int) -> int:
            count = 0
            while True :
                s = n // 2  
                y = n % 2   
                if y == 1:
                    count += 1
                if s == 0 :
                    break
                n = s
            return count
    View Code

    移位运算:

    如果求余数结果为一,则计数然后右移一位,否者直接右移一位。以此类推:直到输入的数字递减为0,退出。

    class Solution:
        def hammingWeight(self, n: int) -> int:
            res = 0
            while n:
                if not n % 2:
                    n = n >> 1
                    continue
                res += 1
                n = n >> 1
            return res
    View Code

    如果输入1,这输出1-9的数字。

    如果输入2,则输出1-99的数字。

    使用循环的方式直接取出:

    class Solution:
        def printNumbers(self, n: int) -> List[int]:
            newList = list()
            for _ in range(1,10**n):
                newList.append(_)
            return newList
    View Code

    使用列表解析:

    class Solution:
        def printNumbers(self, n: int) -> List[int]:
            return [i for i in range(1,10**n)] 
    View Code

    # Definition for singly-linked list.
    # class ListNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    
    class Solution:
        def deleteNode(self, head: ListNode, val: int) -> ListNode:
            if head.val == val: 
                return head.next
            pre, cur = head, head.next
            while cur and cur.val != val:
                pre, cur = cur, cur.next
            pre.next = cur.next
            return head
    View Code
  • 相关阅读:
    从域名锁定该网站所在城市
    微信接口开发 2----接收微信接口返回的数据
    微信接口开发1--向微信发送请求--获取access_token
    MVC-前端设计
    MVC-第一个简单的程序
    MVC-基础02
    MVC-基础01
    表值函数
    视图

  • 原文地址:https://www.cnblogs.com/topass123/p/12563968.html
Copyright © 2011-2022 走看看