首页 > 解决方案 > 为什么我的关于反转位的 C 代码不起作用?

问题描述

我正在编写代码来反转一个无符号整数,其位相同但顺序相反。我的代码在接受用户输入时不会停止运行。我究竟做错了什么?

#include <stdio.h>

unsigned int reverse_bits(unsigned int n);

int main(void) {
        unsigned int n;
        printf("Enter an unsigned integer: ");
        scanf("%u",&n);
        printf("%u\n",reverse_bits(n));
        return 0;
}

unsigned int reverse_bits(unsigned int n) {
        unsigned int reverse = 0;
        while(n>0) {
                reverse <<= 1;
                if((n & 1) == 1) {
                        reverse = reverse^1;
                }
        }
        return reverse;
}

标签: creversebitunsigned-integer

解决方案


在您的程序中,while 条件是检查 n 是否大于零。但是,在循环内部,没有修改 n 的操作。所以请尝试使用它。它会起作用的。

unsigned int reverse_bits(unsigned int n) {
    unsigned int reverse = 0;
    while (n>0) {
            reverse <<=1;
            if((n & 1) == 1) {
                    reverse = reverse | 1;
            }
            n=n>>1;

    }
    return reverse;

}


推荐阅读