Number Complement
Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation.
Example 1:
1 2 3
|
Input: 5 Output: 2 Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2.
|
Example 2:
1 2 3
|
Input: 1 Output: 0 Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0.
|
solution
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
s = [] print("input integer:") x = int(input()) //十进制转换为二进制 while x!=0: s.append(x%2) x = x//2 print(s) //二进制位0,1互换,并将整型转换为字符串类型 temp = "" for i in range(0,len(s)): if 1 & s[i] ==1: s[i] =0 else: s[i] =1 temp+=str(s[i]) //二进制转换为十进制数 print(int(temp,2))
|
note
Python中的进制转换方法:
↓ |
2进制 |
8进制 |
10进制 |
16进制 |
2进制 |
- |
bin(int(x,8)) |
bin(int(x,10)) |
bin(int(x,16)) |
8进制 |
oct(int(x,2)) |
- |
oct(int(x,10)) |
oct(int(x,16)) |
10进制 |
int(x,2) |
int(x,8) |
- |
int(x,16) |
16进制 |
hex(int(x,2)) |
hex(int(x,8)) |
hex(int(x,10)) |
- |
近期评论