当前位置 博文首页 > Liu,:Leetcode——颠倒二进制位

    Liu,:Leetcode——颠倒二进制位

    作者:[db:作者] 时间:2021-07-20 09:41

    1. 题目

    在这里插入图片描述

    2. 题解

    • 使用一个int变量 res存储颠倒后二进制
    • res持续左移,把最后一个位置空出来
    • n往右移一位,把最后一位数字去掉
    • n最后一位数字存入res左移空出来的位置
    • 持续操作32次
    public class Solution {
        // you need treat n as an unsigned value
        public int reverseBits(int n) {
            int res = 0;
            for(int i = 0; i < 32; i++){
                //res持续左移,每次插入n的最后一位,n保持右移
                res = res << 1;
                res = res + (n & 1);
                // n & 1:获取n的最后一位
                n = n >> 1;
            }
            return res;
        }
    }
    
    cs
    下一篇:没有了