位1的个数
Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight).
For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011
, so the function should return 3.
Code(By myself):
class Solution(object):
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
count = 0
s = bin(n)
for i in s:
if i == '1':
count += 1
return count
Code(others):
class Solution(object):
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
counts = 0
while n > 0:
if n & 1 == 1:
counts += 1
n >>= 1
return counts
总结:
bin()将十进制转化为二进制,输出为字符串;>>将二进制右移
汉明距离
The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
Given two integers x
and y
, calculate the Hamming distance.
Note:
0 ≤ x
, y
< 231.
Example:
Input: x = 1, y = 4
Output: 2
Explanation:
1 (0 0 0 1)
4 (0 1 0 0)
↑ ↑
The above arrows point to positions where the corresponding bits are different.
Code(By myself):
class Solution(object):
def hammingDistance(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
a = x ^ y
count = 0
while a > 0:
if a & 1 == 1:
count += 1
a >>= 1
return count
Code(others):
class Solution(object):
def hammingDistance(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
diff = x^y
ret = 0
while diff:
diff &= diff-1
ret += 1
return ret
总结:
diff &= diff - 1会消去二进制最右边的1
颠倒二进制位
Reverse bits of a given 32 bits unsigned integer.Example:
输入: 43261596
输出: 964176192
解释: 43261596 的二进制表示形式为 00000010100101000001111010011100 ,
返回 964176192,其二进制表示形式为 00111001011110000010100101000000 。
Code(By myself):
class Solution:
# @param n, an integer
# @return an integer
def reverseBits(self, n):
s = bin(n)
s = s[2:]
while len(s) < 32:
s = '0' + s
s = s[::-1]
return int(s,2)
Code(others):
class Solution:
# @param n, an integer
# @return an integer
def reverseBits(self, n):
z=bin(n)[2:]
z="0"*(32-len(z))+z
z=z[::-1]
return int(z,2)
杨辉三角
Given a non-negative integer numRows , generate the first numRows of Pascal's triangle.Example:
Input: 5
Output:
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
Code(By myself):
class Solution(object):
def generate(self, numRows):
"""
:type numRows: int
:rtype: List[List[int]]
"""
triangle = []
for i in range(numRows):
Row = [1]
if i >= 1:
j = 1
while j < i:
Row.append(triangle[i-1][j-1] + triangle[i-1][j])
j += 1
Row.append(1)
triangle.append(Row)
return triangle
有效的括号
Given a string containing just the characters '('
, ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid.
An input string is valid if:
- Open brackets must be closed by the same type of brackets.
- Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
Example:
Input: "()"
Output: true
Code(By myself):
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
if len(s) == 0:
return True
if len(s) % 2 != 0:
return False
dic = {
'(' : ')',
')' : '(',
'[' : ']',
']' : '[',
'{' : '}',
'}' : '{'
}
temp = []
for i in s:
if i == '(' or i == '[' or i == '{':
temp.append(dic[i])
else:
if temp ==[]:
return False
else:
if i != temp.pop():
return False
if temp ==[]:
return True
else:
return False
缺失数字
Given an array containing n distinct numbers taken from 0, 1, 2, ..., n
, find the one that is missing from the array.
Example:
Input: [3,0,1]
Output: 2
Code(By myself):
class Solution(object):
def missingNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
length = len(nums)
summ = (length+1) * length / 2
for i in nums:
summ -= i
return summ
Code(others):
class Solution(object):
def missingNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
n = len(nums)
return n*(n+1)/2 - sum(nums)