0422: 11, the number of binary 1; the first common node of the two lists 12

11, the number of binary 1's title described

An integer that indicates the number of the output of the binary number 1 in. Wherein a negative number indicates a complement.
Note: The calculation of the number of negative complement 1, the key is to convert complement negative number can not be written, see the answer to the comments section of ~

Solution 1: n plus 2 ^ 32 represents the complement form of a negative -

# -*- coding:utf-8 -*-
class Solution:
    def NumberOf1(self, n):
        # write code here
        return bin(n).count('1') if n>= 0 else bin(n + 2**32).count('1')
# -*- coding:utf-8 -*-
class Solution:
    def NumberOf1(self, n):
        # write code here
        return sum([(n>>i & 1) for i in range(0,32)])

Solution 2:
Links: https://www.nowcoder.com/questionTerminal/8ee967e43c2c4ec193b040ea7fbb10b8
Source: Cattle-off network

For example: a binary number 1100, from the third to the right of the number is in a rightmost 1. After subtracting 1, the third becomes 0, it later became two of 0 1 1 while the front remains unchanged, so the result is 1011. We found that the results of minus one is to a rightmost 1 bits are all starting to take backwards. This time the results after the original integer if we then do with the operation and subtract 1 from the original integer rightmost 1 the one who began all the bits will become 0. Such as the 1100 & 1011 = 1000. That put an integer minus 1, and then to do with the original integer arithmetic, the integer will rightmost 1 becomes 0. Then a binary integer of 1 how many, how much can be times such an operation.

# -*- coding:utf-8 -*-
class Solution:
    def NumberOf1(self, n):
        # write code here
        if n < 0:
            n = n & 0xffffffff
        count = 0
        while n:
            count += 1
            n = n & (n - 1)
        return count

12, the first two lists common node

Description Title
input two lists, find their first common node.
Note: beginning to write their own code to directly compare two lists of nodes, the result has been not passed, because the value of the list with a pointer? The code is read by
without any increase in .val, plus returns an empty list

# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    def FindFirstCommonNode(self, pHead1, pHead2):
        # write code here
        l = []
        while pHead1:
            l.append(pHead1)
            pHead1 = pHead1.next
        while pHead2:
            if pHead2 in l:
                return pHead2
                break
            else:
                pHead2 = pHead2.next

Guess you like

Origin blog.csdn.net/Leia21/article/details/89526201