二进制十进制转换 bin() int(String,2)

二进制十进制转换

1. 十进制—>二进制 bin() 函数 in Python

Input type: int/ long int

Return type: String

将int/ long int 转换为:二进制表示的String, 数字前面+ “0b”, 表示二进制

1
2
3
S = bin(2)
# S = '0b10'
#'0b'-->表示二进制, '10'-->2的二进制表示方法

用法

既然返回值为String,就可以用String的方式来使用

EX:ans = bin(2^3).count("1")

bin(2^3) —> 0b111

"0b111".count("1")—>3

2. 二进制 —> 十进制: int(,)函数 in Python

int(String 二进制表示,2)

The Input String can directly be the number, or the bin() represents

1
2
3
4
5
I1 = int('11',2)
# I1 = 3

I1 = int('0b11',2)
# I1 = 3

EX: Leetcode 461. Hamming Distance

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:

1
2
3
4
5
6
7
8
9
10
11
> 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.
>
1
2
3
4
5
6
7
8
class Solution:
def hammingDistance(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
return bin(x^y).count("1")