【每日一题11126】反转比特

:mage:t2: 请编写一个函数,将一个十进制数字按二进制位进行反转,求出反转位置后的十进制数字。

示例:
输入:417,输出:267。因为417的二进制是110100001,反转后是`100001011。

题目难度:简单
题目来源:Reverse the bits in an integer

def solution(num: int) -> int:
    # your code

assert solution(417) == 267
assert solution(267) == 417
assert solution(2017) == 1087
def solution(num: int) -> int:
    return int('{0:b}'.format(num)[::-1], 2)


assert solution(417) == 267
assert solution(267) == 417
assert solution(2017) == 1087
1 Like

def solution_11126(num:int)->int:
‘’’
请编写一个函数,将一个十进制数字按二进制位进行反转,求出反转位置后的十进制数字。

示例:
输入:417,输出:267。因为417的二进制是110100001,反转后是`100001011。
:param num:
:return:
'''
bin_num = bin(num)
bin_str = str(bin_num)
bin_str = bin_str[2:]
reverse_str:str = ""
while bin_str is not "":
    reverse_str = reverse_str + bin_str[-1]
    bin_str = bin_str[0:-1]

print(reverse_str)
return int(reverse_str, 2)

def test_solution_11126():
assert solution_11126(417)==267
assert solution_11126(1) == 1
assert solution_11126(2) == 1
assert solution_11126(2017) == 1087

def solution(num: int) -> int:
    return int((''.join([i for i in bin(num)[2:]][::-1])),2)

assert solution(417) == 267
assert solution(267) == 417
assert solution(2017) == 1087
public int solution(int n) {
        ArrayList<Integer> integers = new ArrayList<>();
        // 转换为二进制
        for (int i = 0; i <= 31; i++) {
            integers.add(n >>> i & 1);
        }
        // 去除多余的位数,并转换为String
        String s = "";
        for (int i = integers.size() - 1; i >= 0; i--) {
            if (integers.get(i) != 0) {
                s = integers.stream().limit(i + 1).map(integer -> Integer.toString(integer)).collect(joining(""));
                break;
            }
        }
        // 转换为十进制
        int b = Integer.parseInt(s);
        int decimal = 0;
        int p = 0;
        while (true) {
            if (b == 0) {
                break;
            } else {
                int temp = b % 10;
                decimal += temp * Math.pow(2, p);
                b = b / 10;
                p++;
            }
        }
        return decimal;
    }
def solution(num: int):
    arr = []
    for c in format(num, 'b'):
        arr.insert(0, c)
    return int(''.join(arr),2)
关闭