LeetCode精选TOP面试题190.颠倒二进制位

题目描述

颠倒给定的 32 位无符号整数的二进制位。

示例 1:
输入: 00000010100101000001111010011100
输出: 00111001011110000010100101000000
解释: 输入的二进制串 00000010100101000001111010011100 表示无符号整数 43261596,
      因此返回 964176192,其二进制表示形式为 00111001011110000010100101000000
示例 2:

输入:11111111111111111111111111111101
输出:10111111111111111111111111111111
解释:输入的二进制串 11111111111111111111111111111101 表示无符号整数 4294967293,
      因此返回 3221225471 其二进制表示形式为 10101111110010110010011101101001

在 Java中,没有无符号整数类型。在这种情况下,输入和输出都将被指定为有符号整数类型,并且不应影响算法的实现,在 Java 中,编译器使用二进制补码记法来表示有符号整数。因此,在上面的示例 2 中,输入表示有符号整数 -3,输出表示有符号整数 -1073741825。

解题思路

  • 思路1 :接口实现,一行代码,不香,没有手动实现的乐趣;
  • 思路2 :位运算实现,真香,参考大佬分析的思路叭

代码实现(Java)

/**
 * @author : flower48237
 * @2020/3/18 21:25
 * @title : LeetCode精选TOP面试题190.颠倒二进制位
 * 思路1:接口实现
 */
public class Solution {
    // you need treat n as an unsigned value
    public int reverseBits(int n) {
        return Integer.reverse(n);
    }
}
/**
 * @author : flower48237
 * @2020/3/18 21:25
 * @title : LeetCode精选TOP面试题190.颠倒二进制位
 * 思路2:位运算实现
 */
public class Solution {
    // you need treat n as an unsigned value
    public int reverseBits(int n) {
        int res = 0;
        for (int bitsSize = 31; n != 0; n = n >>> 1, bitsSize--) {
            res += (n & 1) << bitsSize;
        }
        return res;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章